MohammadTofi
MohammadTofi

Reputation: 385

How to reset value of state in a Redux store?

I use redux-persist to save my state in local storge, I need after 5-minute finish to log out a user and move a user to a login page, but I can't remove persist value from local storge, every time I try to remove value using storage.removeItem the redux-persist return the value back.

RootReducer:

import storage from 'redux-persist/lib/storage';
    const appReducer  =  combineReducers({
      auth: authReducer,
      //....
    });
    const rootReducer = (state, action) => {
      if (action.type === SIGNOUT_REQUEST) {
        Object.keys(state).forEach(key => {
          storage.removeItem(`persist:${key}`);
      });
        state = undefined;
    }
    return appReducer(state, action);
    }
    export default rootReducer; 

Logout Action:

export const logoutUser = () => dispatch => {
  dispatch({
    type: SIGNOUT_REQUEST
  })

APP.js

if (isTimeout) {
    store.dispatch(logoutUser());
  }

index.js

ReactDom.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
  , document.querySelector('#root')
);

Upvotes: 1

Views: 8841

Answers (2)

Michael Brenndoerfer
Michael Brenndoerfer

Reputation: 4066

To "reset" your entire redux-persist store use purge()

persistor.purge()

"purge() method only clear the content of the storage, leaving the internal data of redux untouched"

flush() as suggested previously is wrong and only flushes pending states: "flush() method for flushing all pending state serialization and immediately write to disk"

https://nicedoc.io/rt2zz/redux-persist/blob/master/docs/api.md

Upvotes: 3

SamVK
SamVK

Reputation: 3395

You can explicity call persistor.flush() after the dispatch to tell the reducer to immediately save the latest state if necessary.

import { persistor } from 'store'; // or w/e
// ...
export const logoutUser = () => dispatch => {
  dispatch({
      type: SIGNOUT_REQUEST
  });
  persistor.flush();
}

From the developer:

flush is designed to force the writing of all pending state asap, and to provide a promise to wait for the writes resolution. This can be handy for example if you need to ensure latest state is written before navigating away.

Upvotes: 4

Related Questions