1

For logout I have to reset everything, but I have many reducers aka collection of states, I have to do switch(type.LOGOUT): return {} in every reducer in order to reset everything to initialState?

export default combineReducers({
    user,
    tickets,
    settings,
    manyMoreToCome
})
Jamie Aden
  • 943
  • 2
  • 12
  • 20
  • Possible duplicate of [How to reset the state of a Redux store?](https://stackoverflow.com/questions/35622588/how-to-reset-the-state-of-a-redux-store) – RIYAJ KHAN Mar 24 '18 at 09:46

1 Answers1

3

The initialState of your application shoudln't be {}, it's the value you pass when creating the store.

This is also called the preloadedState in case you are implementing a sort of local state persistence...

Thus you usually don't want to break anything and set the state to an empty object, instead you should do something like :

// initialState should be exported somewhere in your application
// when the store is created, and imported in the reducer.
switch(action.TYPE){
    case types.LOGOUT:
    return { ...initialState };
}

It's important that you shouldn't implement any action in more than a reducer combineReducers calls all reducers with the current state, each reducer will return the state as-is if no change is required, thus the type.LOGOUT action should only be on the relevant reducer, that's user or settings depending on the application.

mrbm
  • 2,164
  • 12
  • 11
  • I set it to empty object just to demonstrate I need to catch LOGOUT in every reducers. You said shouldn't implement LOGOUT in more than a reducer because you might not know the problem. If more than one user login and logout the system without refresh do you think I need to clear the setting and user reducer only? For example a user clicked on something, so ticket reducer isn't original, then he logout, the ticket reducer changed isn't clear, causing the problem for the next user who login. – Jamie Aden Mar 24 '18 at 09:58
  • @jamie-aden Since logging out is a user-initiated action, I would recommend to dispatch actions that reset all other reducers affected by this event. I found `mapDispatchToProps` to be a good place for this. You could call `dispatch(ticketActions.reset())` there. This way, the other reducers don't need to be concerned with **why** they should reset something, they're just instructed to reset at the right moment. – timotgl Mar 24 '18 at 13:05
  • thanks for the tip, in the end I did this https://pastebin.com/raw/CLnceSwu – Jamie Aden Mar 24 '18 at 14:47