1

Is there an elegant way to clear out slices of a state? I have 7 slices of data in my state and I want to keep one active while erasing the rest of them. Do I need to run through each of my reducers and manually erase the slices in each one, or is there another way?

Thanks in advance...

nikotromus
  • 1,015
  • 16
  • 36

2 Answers2

4

You could do the following:

const resetState = () => ({
  type: 'RESET_STATE'
})

const appReducer = combineReducers({
  /* your app’s top-level reducers */
})

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

  return appReducer(state, action)
}

function resetAndUpdateOneSlice() {
  return (dispatch, getState) {
    const slice = Object.assign({}, getState().slice) 
    //assuming your slice is an object
    //just want to demonstrate cloning your data before you reset your state.
    dispatch(resetState())
    dispatch(updateSliceOfState(slice))
  }
}

This is one possible solution - a mixture of pure functions and thunks - though I'm not sure why you want to reset so many parts of your state. Not that I'm condemning your decision, I'm just trying to figure out a use case that's not entirely contrived.

The following is possible since we're using pure functions.

Also, I'm referencing this article, since it was quite helpful.

How to reset the state of a Redux store?

Hope this helps

Community
  • 1
  • 1
Sean Kwon
  • 907
  • 6
  • 12
  • When the user hits the logout button, we need the entire state cleared. However, when they hit the home button, we need the slices of the state cleared for the object they were building in the application. We do NOT want things like their login credentials cleared. Does that make sense as to why we want specific pieces of the state cleared? – nikotromus Feb 23 '17 at 15:18
  • yes, that's a good use case then. The article I referenced definitely applies to your case then – Sean Kwon Feb 23 '17 at 15:21
0

The best solution I found was to utilise the extraReducers functionality when creating the slice. This allowed the slice to listen to other events and achieve what I was looking for.

Ref: https://redux-toolkit.js.org/api/createSlice#extrareducer

import { LOGOUT_USER } from '../redux/actions';
...
const reducerResult = createSlice({
      name: slice,
      initialState: initialState[state],
      reducers: this._generateReducers(),

      extraReducers: (builder) => {
        builder.addCase(LOGOUT_USER, (state, action) => {
          return { ...this.initialState };
        });

        // Default case if no other handlers matched
        //.addDefaultCase((state, action) => {});
      },
    });
Liam
  • 697
  • 8
  • 16