2

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)

asus
  • 1,427
  • 3
  • 25
  • 59

1 Answers1

3

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)
}
phry
  • 35,762
  • 5
  • 67
  • 81
  • nothing seems to happen when I dispatch this action from my logout handler. `await dispatch(resetAction())` does not call the `resettableReducer`. – asus Aug 26 '20 at 17:05
  • 1
    Are you using the `resettableReducer` instead of the `reducer` now? It's a wapper around the `reducer`, so everywhere you used `reducer` before, you should use the `resettableReducer` now or it will never be called. For example in your `persistedReducer` definition. – phry Aug 27 '20 at 06:52
  • Ah yes, you are right. Guess that wasn't utterly obvious. Thanks! – asus Aug 28 '20 at 17:51
  • If you have an authorizationSlice, couldn't you just write a reducer in that slice and have it set state to undefined whenever the logout() function is called? For example, `logout : state => { state = {userInfo: {}, expiresAt: null, isLoggedIn: false} }` or simply `logout : state => { state = undefined}` –  Sep 06 '20 at 16:47