-
-
Notifications
You must be signed in to change notification settings - Fork 15.2k
Add store.resetState for reverting to initial state value #658
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
We do this in fluxette. |
I don't think there is a need for this in core. Store API must be as simple as possible so it's easy to write extensions like Redux DevTools. See how to implement this in userland: function makeHydratable(reducer, hydrateActionType) {
return function (state, action) {
switch (action.type) {
case hydrateActionType:
return reducer(action.state, action);
default:
return reducer(state, action);
}
}
} Usage: const HYDRATE_STATE = 'HYDRATE_STATE';
const reducer = combineReducers(myReducers);
const hydratableReducer = makeHydratable(reducer, HYDRATE_STATE);
const store = createStore(hydratableReducer, initialState);
// later
store.dispatch({
type: HYDRATE_STATE,
state: initialState
}); |
I assume you'd need to also |
Right! |
Oh wait, you wouldn't need to. Just pass |
Here's the fixed version: function makeHydratable(reducer, hydrateActionType) {
return function (state, action) {
switch (action.type) {
case hydrateActionType:
return reducer(action.state, action);
default:
return reducer(state, action);
}
}
} |
Awesome, so obvious now! |
@gaearon I don't see a reason to call the reducer when the action is hydrateActionType, I don`t think any reducer should handle this action. I understand that the reducers would all ignore it and return state as is, so why not short-circuit the reducer returning action.state? I am probably missing something, but I have it implemented this way.. |
The author wanted to be able to specify non-full state, and have reducers return initial state in this case: #658 (comment). |
@tgriesser Why would you do this: function replaceState(newState) {
currentState = newState;
dispatch({ type: ActionTypes.INIT });
} Instead of this: function resetState() {
currentState = {};
dispatch({ type: ActionTypes.INIT });
} What's the point of |
I have a situation where I'd like to reset the entire app state to the original value (after
ActionTypes.INIT
is run), but couldn't find a clean way to write it as a plugin without replacing the majority ofcreateStore
.I can also imagine situations where you'd want to replace the entire
currentState
with a new value, for example if you wanted to re-hydrate the entire app state from a different serialized session.So I wanted to see if this
resetState
or an alternate more genericreplaceState
seemed like a good enough use case to add to the core API. ThereplaceState
would look similar to this PR, but would pass in the state value and then run the init dispatch: