0.1.7 • Published 5 months ago

react-drstore v0.1.7

Weekly downloads
-
License
-
Repository
github
Last release
5 months ago

Minimalistic React store.

Step back of current obscure store-state managers.

(!) Warning: Not production-ready Yet!

  • TypeScript-ed! So you can view your states' structure and methods arguments when accessing via subscribeSelector(), useContext(), 'store', etc.

  • Also works with React-Native (ofcourse)

  • Supports Local Storage from-the-box
  • Supports async Actions
  • Also brings back old style setState with merge state instead: { level: 3 } --> set({ name: 23 }) --> { level: 3, name: 23 }, And also /\ it is with deep merge, so you can use it like this: { name: { b: 32 } } --> set({ name: { a: 23 } }) --> { name: { b: 32, a: 23 } }

There're plans to abstract it and make framework-free version. Also there's a plan to bring back old cool feature as having prevState in update subscriber


Examples:

Declaring Slices:

type GameStateType = {
  level: number
  score: number
}
type GameStateActions = {
  levelUp: StateAction<number, boolean>,
  // for async actions, use 'StateAction<number, Promise<boolean>>'
}

type SettingsType = {
  notifyByEmail: boolean
}

type AppSlicesDesc = {
  gameState: Slice<GameStateType, GameStateActions>
  settings: Slice<SettingsType, {}>
}

const AppSlices: AppSlicesDesc = {
  gameState: {
    initialState: {
      level: 2,
      score: 36,
    },
    actions: (set: StoreSet<any>) => ({
      levelUp: () => {
        set(curLvl => curLvl + 1)
      },
      // could also use 'async' here
    }),
  },
  settings: {
    initialState: {
      notifyByEmail: false,
    },
  },
}

App, wrapping into Provider:

const { DRStoreContext, DRStoreProvider, store } = createStore(AppSlices)
export { DRStoreContext, store }

function App() {
  return (                       // 'LoadingScreen' is optional. See docs for more info
    <DRStoreProvider LoadingScreen={MyLoadingScreenComponent}>
      <MyComponent>
    </DRStoreProvider>
  );
}

Using store inside component:

import { store } from '... App'

export const MyComponent = ({}) => {
  const lvl = store.subscribeSelector(state => state.gameState.level)

  const onButtonClick = () => {
    store.actions.gameState.levelUp()
  }

  return (
    <div>
      <div>
        Current Level:
        { lvl }
      </div>
      <div onClick={onButtonClick}>
        'level-up'
      </div>
    </div>
  )
}

Installation: npm

npm i --save react-drstore @react-native-async-storage/async-storage
cd ios && pod install

And see example from above.


todo:

  • Middleware
  • Temp: Temporary dependency is latest version of React. But it will be minified to lowest compatible version (probably some version from ~2018--19).
  • todorefactor allow '...args' instead of using payload-object for actions with args > 1. But maybe will leave as is, will see if that's needed / more convenient for people