Amir Shahbabaie
Amir Shahbabaie

Reputation: 1412

How to delete redux state on logout using the history object

In old days when I wanted to clear a redux store upon logout for example, in my main reducer, I would do:

const appReducer = (state, action) => combineReducers(
    {myreducer1,
    myreducer2} 
)(state, action)

const rootReducer = (state, action) => {
    if (action.type === 'LOGIN_LOGGED_OUT') {
        state = undefined
    }
    return appReducer(state, action)
}

export default rootReducer;

but the new version of redux just sends a history object so I cannot access my state and actions anymore, so I cannot clear my reducer. Any ideas how I can change this code to work as the above code?

const rootReducer = (history) => combineReducers({ 
    {myreducer1,
    myreducer2} 
    )

Upvotes: 1

Views: 837

Answers (1)

Drew Reese
Drew Reese

Reputation: 203348

const rootReducer = (history) => 
  combineReducers({ 
    myreducer1,
    myreducer2,
  });

This returns a reducer function, so you can create another higher order reducer function. For example, this is how my team handles resetting state.

const reducer = history =>
  combineReducers({
    .... all the reducers
  });

const reducerWithReset = history => (state, action) => {
  let resetState;

  switch (action.type) {
    case RESET_STATE:
      resetState = undefined;
      break;

    case LOGOUT_SUCCESS:
      resetState = deriveLogoutState(state);
      break;

    .... other cases

    default:
      resetState = state;
  }
  return reducer(history)(resetState, action);
};

export default reducerWithReset;

Then when initializing the redux store we are using the exported reducerWithReset "rootReducer" and just pass a history object to it.

configureStore({
  devTools: {
    .....
  },
  reducer: rootReducer(history),
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware({
      .... configs
    }).concat(
      .... additional middlewares
    ),
  preloadedState: state,
});

Upvotes: 1

Related Questions