Redux-toolkit: What would be best way to reset the full nested state.

Created on 13 May 2020  路  2Comments  路  Source: reduxjs/redux-toolkit

let say I have my store with nested combineReducers as below

const rootReducer = () =>
combineReducers({
agent,
customer: customerReducer
});

const customerReducer = combineReducer({
profile,
account
})

In this case if I want to reset the full customer state to its initial state how can I do that?

Note: "@reduxjs/toolkit": "^1.3.5",
"typescript": "^3.8.3"

Most helpful comment

Somehow I seem to have missed this ticket.

You can also do something like

const resettableRootReducer = (state, action) => {
  if (action.type === 'store/reset') {
    return rootReducer(undefined, action);
  }
  return rootReducer(state, action);
}

All 2 comments

I personally prefer to create a single "destroy" (or logout) action that I then make each reducer subscribe to. This action should make the reducer return the initial state.

If you want to achieve this by using the combined reducer. You first need to combine your initial state as well. AFAIK, Redux doesn't provide such utility.

I have a NextJS app that uses the NextJS redux wrapper. It magically provides the initial combined state to my Redux store. Here's how I have it setup:

import {

combineReducers, AnyAction, Reducer,

} from 'redux';

import { HYDRATE } from 'next-redux-wrapper';

import { reducer as userReducer } from './user/reducer';

import { reducer as profileReducer } from './profile/reducer';

import { reducer as playlistsReducer } from './playlists/reducer';

import { reducer as playlistItemsReducer } from './playlistItems/reducer';

import { reducer as tracksReducer } from './tracks/reducer';

import { reducer as tracksAudioFeaturesReducer } from './tracksAudioFeatures/reducer';

import { CombinedStateType } from './types';

const allReducers = {

user: userReducer,

profile: profileReducer,

playlists: playlistsReducer,

playlistItems: playlistItemsReducer,

tracks: tracksReducer,

tracksAudioFeatures: tracksAudioFeaturesReducer,

};

export const combinedReducer = combineReducers(allReducers);

export const rootReducer: Reducer = (

state: CombinedStateType, action: AnyAction,

): CombinedStateType => {

if (action.type === HYDRATE) {

return {

...state,

...action.payload,

};

}

return combinedReducer(state, action);

};


[EDIT]

Sorry about the bad formatting, posting from mobile.

Somehow I seem to have missed this ticket.

You can also do something like

const resettableRootReducer = (state, action) => {
  if (action.type === 'store/reset') {
    return rootReducer(undefined, action);
  }
  return rootReducer(state, action);
}

Was this page helpful?
0 / 5 - 0 ratings