简体   繁体   中英

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')
);

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM