I am using Redux for state management.
How do I reset the store to its initial state?
For example, let’s say I have two user accounts (u1
and
Define an action:
const RESET_ACTION = {
type: "RESET"
}
Then in each of your reducers assuming you are using switch
or if-else
for handling multiple actions through each reducer. I am going to take the case for a switch
.
const INITIAL_STATE = {
loggedIn: true
}
const randomReducer = (state=INITIAL_STATE, action) {
switch(action.type) {
case 'SOME_ACTION_TYPE':
//do something with it
case "RESET":
return INITIAL_STATE; //Always return the initial state
default:
return state;
}
}
This way whenever you call RESET
action, you reducer will update the store with default state.
Now, for logout you can handle the like below:
const logoutHandler = () => {
store.dispatch(RESET_ACTION)
// Also the custom logic like for the rest of the logout handler
}
Every time a userlogs in, without a browser refresh. Store will always be at default.
store.dispatch(RESET_ACTION)
just elaborates the idea. You will most likely have an action creator for the purpose. A much better way will be that you have a LOGOUT_ACTION
.
Once you dispatch this LOGOUT_ACTION
. A custom middleware can then intercept this action, either with Redux-Saga or Redux-Thunk. Both ways however, you can dispatch another action 'RESET'. This way store logout and reset will happen synchronously and your store will ready for another user login.