Resetting redux state on logout
You can make an action for clearing the store and use it in your rootReducer
as like this:
const appReducer = combineReducers({
... // your reducers
});
const rootReducer = (state, action) => {
if (action.type === 'CLEAR_STORE') return appReducer(undefined, action);
return appReducer(state, action);
};
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const configureStore = (initialState, history) =>
createStore(
connectRouter(history)(rootReducer),
initialState,
composeEnhancers(applyMiddleware(routerMiddleware(history), thunkMiddleware))
);
You'll have appReducer
with all your reducers but also rootReducer
which will be the function that will determinate returning a corresponding value or an undefined one.
TIP: You can use your Logout action rather than using a new action just for clearing the store
I wanted to point out to a couple of things that are pretty important before I give you a solution:
When using redux you should never attempt to alter the state of your store directly. The state should always change through the reducer as a reaction to an action. Therefore, reassigning the parameter
initialState
inside thatsubscribe
callback is incorrect and pointless.I don't think that you want to "reset" the state of the
router
property, correct?
One way to solve this is to use a reducer enhancer, something like this:
const resetEnhancer = rootReducer => (state, action) => {
if (action.type !== 'RESET') return rootReducer(state, action);
const newState = rootReducer(undefined, {});
newState.router = state.router;
return newState;
};
And then when you create your store do this:
const store = createStore(
resetEnhancer(createRootReducer(history)),
initialState,
composeEnhancers(applyMiddleware(...middleware), ...enhancers)
);
And in that subscribe
callback do this:
if (!session) {
store.dispatch({type: 'RESET'});
}
One last extra-tip: since you are using redux-saga
I strongly suggest that you move what you are doing inside that subscribe
callback into a saga.