in React JS by
Q:

How to reset state in Redux?

1 Answer

0 votes
by

You need to write a root reducer in your application which delegate handling the action to the reducer generated by combineReducers().

For example, let us take rootReducer() to return the initial state after USER_LOGOUT action. As we know, reducers are supposed to return the initial state when they are called with undefined as the first argument, no matter the action.

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

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

  return appReducer(state, action)
}

In case of using redux-persist, you may also need to clean your storage. redux-persist keeps a copy of your state in a storage engine. First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and clean each storage state key.

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

const rootReducer = (state, action) => {
  if (action.type === 'USER_LOGOUT') {
    Object.keys(state).forEach(key => {
      storage.removeItem(`persist:${key}`)
    })

    state = undefined
  }

  return appReducer(state, action)
}
Click here to read more about React JS
Click here to read more about Insurance

Related questions

0 votes
asked Mar 4, 2020 in React JS by JackTerrance
0 votes
0 votes
asked Mar 4, 2020 in React JS by JackTerrance
0 votes
0 votes
asked Jun 19, 2020 in React JS by JackTerrance
0 votes
asked Mar 3, 2020 in React JS by miceperry
0 votes
asked Mar 30, 2020 in React JS by amita rallin
...