Home > other >  How to rest redux-tool-kit multi states at once?
How to rest redux-tool-kit multi states at once?

Time:11-26

I have multi initial states like following, the real life example is way bigger but I don't want to over complicate things here, and I want to return all of those sates to default after logging the user out of react app since not resting those states are causing all sorts of bugs if the user relogs ... should I create a special rest function and rest each state separately meaning calling 3 rest separate functions for each state , or is there something that is integrated in to redux tool kit that might be better of a practice to implement ?

my current store config looks like the following

import { configureStore } from '@reduxjs/toolkit';
import stateAReducer from './aSlice';
import stateBReducer from './bSlice';
import stateCReducer from './cSlice';

export const store = configureStore({
  reducer: {
    a: stateAReducer,
    b: stateBReducer,
    c: stateCReducer,
  },
});
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

// Slice A 

const initialState: aState = {
  data1: { name: '', title: '', customColor: '' },
  data2: { linkA: '', linkB: '' },
  img: null,
  online: false,
};

// Slice B 
const initialState: bState = {
  obj1 : {}
  obj2 : {}
  arr : []
};


// Slice C 
const initialState: cState = {
   x : false
   z : true
   f : true
};

current solution ?

 reducers: {
    restAState: (state, action: PayloadAction<>) => {
      state = initialState
    },

CodePudding user response:

I assume that your current reducer will look like this

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export default configureStore({
  reducer: {
    counter: counterReducer,
    // ... more reducers
  },
});

So instead of this approach we can make use of combinereducers

const combinedReducer = combineReducers({
  counter: counterReducer,
  // ... more reducers
});

Followed by

const rootReducer = (state, action) => {
  if (action.type === 'counter/logout') { // check for action type 
    state = undefined;
  }
  return combinedReducer(state, action);
};

export default configureStore({
  reducer: rootReducer,
  middleware: [...getDefaultMiddleware()]
});

Here is my working example where you can see that the inital value gets back to default . You can add as many reducers as you want and all will return to default initial value based on a single action.

  • Related