Files
react-mutable-store/README.md

2.1 KiB

react-mutable-store

Mutatable global stores for React, inspired by Vuex. Uses immer to provide immutable state objects with a mutable API.

GitHub license Project Status

Usage

createStore(name, spec)

Used to create a store. You provide a name and a spec, which is very similar to the way you define a store in Vuex.

The name value is used to access the store with the useState hook (see below).

createStore('counter', {
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
});

<StateProvider />

A React component used to provide all of the created stores as context. You can wrap your entire app in this component to get access to all of the stores that exist. Alternatively, the component takes a names prop string that you can use to control which store providers are used. The string should be a comma-delimited list of stores by name.

<StateProvider>
  <App />
</StateProvider>

useStore(name)

A React hook to access the store's state value, and methods to read and update it. The hook returns an object with the following properties:

Property Description
state The current state value of the store.
commit(name, ...args) Executes mutations, which synchronously change the state and update context, causing components that use the context to re-render.
dispatch(name, ...args) Fires actions, which perform async work and use mutations to update state. Returns a Promise that resolves when the action is complete.
get(name, ...args) Access to any defined getters in the spec. It's a way to define calculated values from the state.

License

MIT © w33ble