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 u2
).
Imagine the following sequence of events:
User
u1
logs into the app and does something, so we cache some data in the store.User
u1
logs out.User
u2
logs into the app without refreshing the browser.
At this point, the cached data will be associated with u1
, and I would like to clean it up.
How can I reset the Redux store to its initial state when the first user logs out?
The following solution works for me.
First on initiation of our application the reducer state is fresh and new with default InitialState.
We have to add an action that calls on APP inital load to persists default state.
While logging out of the application we can simple reAssign the default state and reducer will work just as new.
Main APP Container
Main APP Reducer
On Logout calling action for resetting state
Hope this solves your problem!
You can also fire an action which is handled by all or some reducers, that you want to reset to initial store. One action can trigger a reset to your whole state, or just a piece of it that seems fit to you. I believe this is the simplest and most controllable way of doing this.
in server, i have a variable is: global.isSsr = true and in each reducer, i have a const is : initialState To reset the data in the Store, I do the following with each Reducer: example with appReducer.js:
finally on the server's router:
The accepted answer helped me solve my case. However, I encountered case where not-the-whole-state had to be cleared. So - I did it this way:
Hope this helps someone else :)
Just an extension to @dan-abramov answer, sometimes we may need to retain certain keys from being reset.
My workaround when working with typescript, built on top of Dan's answer (redux typings make it impossible to pass
undefined
to reducer as first argument, so I cache initial root state in a constant):