Search code examples
reactjsreduxreact-reduxconnected-react-router

How to reset the state of a Redux store using connected-react-router?


I'm trying to acheive this exact same behaviour How to reset the state of a Redux store?. except I'm using connected-react-router. My Configuration looks like this:

Reducer

export const rootReducer = history => combineReducers({
    auth: auth.reducer,
    router: connectRouter(history),
    authentication: authenticationReducer,
    users: usersReducer,
    project: projectReducer,
    domain: domainReducer,
    test: testReducer
});

Store

export const history = createBrowserHistory({ basename: '/metro' });

const sagaMiddleware = createSagaMiddleware();
const middleware = [
  ...getDefaultMiddleware({
    immutableCheck: false,
    serializableCheck: false,
    thunk: true
  }),
  sagaMiddleware,
  routerMiddleware(history)
];

const store = configureStore({
  reducer: rootReducer(history),
  middleware,
  devTools: process.env.NODE_ENV !== "production",
  enhancers: [reduxBatch]
});

I tried, but does not work:

const appReducer = (state, action, history) => combineReducers({
    auth: auth.reducer,
    router: connectRouter(history),
    authentication: authenticationReducer,
    users: usersReducer,
    project: projectReducer,
    domain: domainReducer,
    test: testReducer
})

export const rootReducer = history => (state, action) => {
    if (action.type === actionTypes.LOGOUT_SUCCESS) {
        state = undefined;
    }
    return appReducer(state, action, history)
};

Solution

  • This seems to be a known issue with this package. The solution seems to be setting the state to an initialState value, instead of undefined. The only caveat is that you shouldn't try to re-initialize the router–it should do this by default.

    const appReducer = (state, action, history) => combineReducers({
        auth: auth.reducer,
        router: connectRouter(history),
        authentication: authenticationReducer,
        users: usersReducer,
        project: projectReducer,
        domain: domainReducer,
        test: testReducer
    })
    
    const initialState = {
        // Don't reset router here
        auth: {},
        authentication: {},
        users: {},
        project: {},
        domain: {},
        test: {}
    }
    
    export const rootReducer = history => (state, action) => {
        if (action.type === actionTypes.LOGOUT_SUCCESS) {
            state = initialState;
        }
        return appReducer(state, action, history)
    };