React-redux: clear store

Created on 28 Mar 2016  路  4Comments  路  Source: reduxjs/react-redux

hi, when my app cancellation, replacement account to log in again, store the saved data will be reloaded in, how do I clear the data store锛孖t becomes a new store?

All 4 comments

As far as I know there is no built-in way to restore the initial state, but it is easy enough to add this ability :)

I like to use an action that resets the state to the default state.

Here's an example, say, for an online store:

// This would be your initial state. 
// Could just be an empty object.
const initialState = {
  cart: []
}

function reducer(state = initialState, action) {
  switch (action.type) {

    // ... actions like ADD_TO_CART, etc

    case RESET:
      // By adding a `RESET` action, we can dispatch this to re-initialize our store.
      // You can dispatch this action on logout, or whenever you need to reset.
      return initialState;

   default:
      return state;
}

This is different than destroying and re-creating the store, but I believe it would have the same effect.

Note that this is a Redux-specific question, and not a React-Redux concern.

@joshwcomeau's example is good. There's also utilities out there that make that approach easier, such as https://github.com/omnidan/redux-recycle. There are a number of Redux-related libs listed over at https://github.com/markerikson/redux-ecosystem-links , and some of them might also help with this.

If you have other usage questions, please ask them over on Stack Overflow: http://stackoverflow.com/ .

Thank @joshwcomeau for that. It's working for me.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

julienvincent picture julienvincent  路  4Comments

sajaddp picture sajaddp  路  3Comments

owinter86 picture owinter86  路  3Comments

nainardev picture nainardev  路  3Comments

winterbe picture winterbe  路  3Comments