But usually I have sub-stores, how do I reset the whole store part and sub-parts efficiently? I have to call reset for each sub-store:
import { barcode } from './stages/barcode/_barcode'
import { wifi } from './stages/wifi/_wifi'
const init = {
stage: undefined,
barcode: undefined,
}
export const register = {
...init,
stages: {
barcode,
wifi,
},
resetAction: action(state => init),
reset: thunk((actions, _payload, { getState }) => {
actions.resetAction()
actions.stages.barcode.resetAction()
actions.stages.wifi.resetAction()
}),
Or maybe walk down the tree, search reset() and call it.
Is there some idea on a better solution?
Hey @lishine
Reseting the whole store, i.e. placing the reset on the root, should reset all the sub-stores too. 馃憤
Quick reference...
let initialState = {}
const store = createStore({
...,
reset: action((state, payload) => ({
...initialState,
}),
});
initialState = store.getState();
// Later... reset store
store.dispatch.reset();
Oh, I got it ! Cool!
I went further, in order not to import the initialState into store part file, I put it into store root.
But it got ugly.
Is it possible to have access to the Store State in actions?
model:
const storeStructure = {
initialState: {},
setInitialState: action((state, initialState) => {
state.initialState = initialState
}),
reset: action(state => {
const { initialState, ...rest } = state
Object.assign(state, rest)
}),
test,
register,
creating:
export const makeStore = (initialState, options) => {
const store = createStore(storeStructure, { initialState })
store.dispatch.setInitialState(store.getState())
store part:
export const register = {
resetAction: action((state, initialState) => initialState),
reset: thunk((actions, __payload, { getStoreState }) => {
actions.resetAction(getStoreState().initialState.register)
}),
Also, the reset happens unpredictably because thunk is used, some not sync nature
Hey @lishine
Is there any chance you could create a minimal example in codesandbox that illustrates the issues you are facing. I would be happy to help you debug it and come up with a solution then. I have a few ideas forming. 馃憤
I hope I will do it. The only real misunderstanding of mine is the nature of thunk #179 . If it is async, of course I would not want to use it for reset. And I will use it carefully anyway.
For the reset, currently I use import initState and it is fine. Init integrated into the store is just nice to have.
BTW, the initState assignment should be done only in the first createStore in case of SSR:
export const makeStore = (updatedState, options) => {
const store = createStore(storeStructure, { initialState: updatedState })
if (!updatedState) {
initialState = store.getState()
}
if (process.browser) {
subscribe = initSubscriber(store)
}
return store
}
Most helpful comment
Hey @lishine
Reseting the whole store, i.e. placing the reset on the root, should reset all the sub-stores too. 馃憤
Quick reference...