29
loading...
This website collects cookies to deliver better user experience
async
/await
;npm install @rematch/core
const countModel = {
state: 0,
reducers: {
increment(state, payload) {
return state + payload;
},
},
effects: (dispatch) => ({
async incrementAsync(payload) {
await new Promise((resolve) => setTimeout(resolve, 1000));
dispatch.count.increment(payload);
},
}),
};
createModel()
helper for type interference.state
- For defining initial state;reducers
- To contain pure functions for conducting state changes;effects
- For async side-effects.countModel
contains the counter state, as well as the reducers and effects to change it.init()
function.import { init } from "@rematch/core";
// ...
const store = init({
models: {
count: countModel,
},
});
init()
function accepts a config object with properties like models
or plugins
and returns a fully-configured Redux store with additional Rematch functionality.countModel
- here registered under a name count
.dispatch()
or subscribe()
. On top of that, Rematch inserts there its own, custom features like the addModel()
method for lazy-loading new models or shortcut action dispatchers under dispatch
. The latter is especially helpful in changing your state.// ...
const { dispatch } = store;
dispatch({ type: "count/increment", payload: 1 });
dispatch.count.increment(1);
dispatch({ type: "count/incrementAsync", payload: 1 });
dispatch.count.incrementAsync(1);
dispatch[MODEL_NAME]
. Personally, I consider this approach much cleaner and more enjoyable than a direct dispatch()
function.