0

I have a problem with Redux, where my store is reset to the initial state when I change or reload the current page.

I wan't to add a counter on my site that keep the current number, after changing or reloading the page. I have a "+" and a "-" buttons, that works great, but value is reset to 0 when I reload my page.

components/layout.js :

const initialState = {
  count: 0,
}

function reducer(state = initialState, action) {
  console.log("reducer", state, action)
  switch (action.type) {
 //... some actions...
  }
}

const store = createStore(reducer)

export default ({ children }) => (
  <Provider store={store}>
      ...
  </Provider>

Expected: counter keep the value after reloading page
Actual: counter reset to 0 after reloading page

Dave Newton
  • 152,765
  • 23
  • 240
  • 286
Pivil
  • 31
  • 2
  • Redux state is stored in memory. Unless you save and restore it yourself (server-side, localstorage, etc), it won't be available after a refresh or page change. – Emile Bergeron Oct 08 '19 at 14:51
  • 1
    Redux state isn't persisted on page reload. If you want it to stay on hard refresh you check out [this question](https://stackoverflow.com/questions/37195590/how-can-i-persist-redux-state-tree-on-refresh) – Maria Oct 08 '19 at 14:52
  • 1
    Possible duplicate of [How can I persist redux state tree on refresh?](https://stackoverflow.com/questions/37195590/how-can-i-persist-redux-state-tree-on-refresh) – Emile Bergeron Oct 08 '19 at 14:52

2 Answers2

4

it is the expected behavior. Redux does not persist the app state, it is reset when the app is refreshed. However, there are a couple of things you can do to persist you app state:

  1. Since your state is just a count you can store it in localStorage and get the state from localStorage when your app start (i.e. on refresh).
  2. You can use redux-persist to persist your app state, although redux--persist also uses localStorage internally but it gives you more control on how you can persist your state.

Happy coding!

rzwnahmd
  • 942
  • 2
  • 8
0

By reloading of the page you reinit your application and reinit its store. You can store the count value to localStorage and use it after page refresh.

Roman Unt
  • 743
  • 4
  • 8