imransilvake
imransilvake

Reputation: 3

Redux/toolkit reset all states on logout except one

I would like to reset all my redux objects except one (at the moment). The code I am using is working but I think it's not efficient because each time when I add a new slice, I have to update the code below:

// app reducers
const combinedReducer = combineReducers({
    auth,
    general,
    books,
    authors,
    events
});

// reducers type
export type AppReducerType = ReturnType<typeof combinedReducer>;

// root reducer
const rootReducer = (rootState: AppReducerType | undefined, action: AnyAction) => {
    // terminate the state of a redux store
    if (action.type === 'Auth/terminate') {
        if (rootState) {
            rootState = {
                ...rootState,
                auth: aState,                   // reset state
                general: rootState.general,     // keep it as it is
                books: bState,                  // reset state
                authors: auState,               // reset state
                events: eState,                 // reset state
            };
        }
    }
    return combinedReducer(rootState, action);
};
export default rootReducer;

if I use rootState = undefined then it resets all the states including general which I don't want. Is there a better way to achieve the above functionality?

Upvotes: 0

Views: 2127

Answers (1)

markerikson
markerikson

Reputation: 67577

In general, your options are:

  • Have each individual slice reset its own state in response to that same action
  • Keep around a copy of the initial state, and do something like:
return {
  ...initialRootState,
  auth: state.auth
}

Upvotes: 2

Related Questions