Resetting Zustand stores #2829
-
In the documentation, we are given the following code for resetting stores: import { create as _create } from 'zustand'
import type { StateCreator } from 'zustand'
const storeResetFns = new Set<() => void>()
const resetAllStores = () => {
storeResetFns.forEach((resetFn) => {
resetFn()
})
}
export const create = (<T extends unknown>() => {
return (stateCreator: StateCreator<T>) => {
const store = _create(stateCreator)
const initialState = store.getState()
storeResetFns.add(() => {
store.setState(initialState, true)
})
return store
}
}) as typeof _create A similar technique is recommended when writing tests involving zustand. However, if the Perhaps a better way to do this reset might be: rather than storing an initial state to recall on reset, to re-run the state creator instead? export const create = (<T extends unknown>() => {
return (stateCreator: StateCreator<T>) => {
const store = _create(stateCreator)
storeResetFns.add(() => {
store.setState(stateCreator(store.setState, store.getState, store), true);
});
return store
}
}) as typeof _create Is this sensible? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
@biggyspender did you tried with |
Beta Was this translation helpful? Give feedback.
so something like this:
should be like this