Redux Toolkit - Reseting state

Viewed 1192

Following Dan Abramov's approach here, how would I clear my entire application state using RTK?

Dan's suggestion

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

  return appReducer(state, action)
}

my approach - (no idea what Im doing btw)

const reducer = combineReducers({
  user,
  post,
})

const clearState = createAction('CLEAR_STATE')

const rootReducerRTK = createReducer(
  {},
  {
    [clearState.type]: state => (state = undefined), // this is wrong for sure
  },
)

const persistedReducer = persistReducer(persistConfig, reducer)

// ignore all the action types from redux-persist as specified in the docs
export const store = configureStore({
  reducer: persistedReducer,
  middleware: getDefaultMiddleware({
    serializableCheck: {
      ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
    },
  }),
})

export const persistor = persistStore(store)

1 Answers

The point is that Dan is calling appReducer(undefined, action). This generates a new "empty" state.

You need to write a reducer for that by hand - you can still use RTK everywhere else.

const reducer = combineReducers({
  user,
  post,
})

const resetAction = createAction('reset')

const resettableReducer = (state, action) => {
  if (resetAction.match(action) {
    return reducer(undefined, action)
  }
  return reducer(state, action)
}
Related