React Redux state is lost at page refresh

redux state not persisting
redux-persist reset store
save redux state to database
react handle page refresh
cache redux store
redux save state to server
react redux persist npm
react-router clear state on refresh

in my react app I have 3 components. from the 1st component by a button, I use Link to go to the 2nd component. at the 2nd I create a state (redux store), manipulate it and when manipulation is finished by submitting button I redirect to the 3rd component. at the 3rd component, I also see the state (by redux chrome tool) but here when I refresh the page (the webpack thing when a code is changed and saved), I lose the sate and get an empty Object.

this is the structure of my app.

index.js

const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <Route component={App} />
    </Provider>
  </BrowserRouter>,
  document.getElementById("root")
);

App.js

const App = ({ location }) => (
  <Container>
    <Route location={location} path="/" exact component={HomePage} />
    <Route location={location} path="/GameInit" exact component={GameInit} />
    <Route location={location} path="/Battle" exact component={Battle} />
  </Container>
);

App.propTypes = {
  location: PropTypes.shape({
    pathname: PropTypes.string.isRequired
  }).isRequired
};

export default App;

Here at HomePage, I have a button that links to GameInit

const HomePage = () => (<Button color="blue" as={Link} to="/GameInit">START GAME</Button>);
export default HomePage;

and the GameInit Page looks like

class GameInit extends Component {
  componentWillMount() {
    const { createNewPlayer} = this.props;
    createNewPlayer();
  }
/* state manipulation till it gets valid */
 palyerIsReady()=>{ history.push("/Battle");}

export default connect(mapStateToProps,{ createNewPlayer})(GameInit);

and finally Battle component where I first see the state but lose on refresh

class Battle extends Component {
  render() {return (/*some stuff*/);}}

Battle.propTypes = {
  players: PropTypes.object.isRequired // eslint-disable-line
};
const mapStateToProps = state => ({
  players: state.players
});
export default connect(mapStateToProps,null)(Battle);

You can easily persist it in the localstorage. Check the example below.

const loadState = () => {
  try {
    const serializedState = localStorage.getItem('state');
    if(serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (e) {
    return undefined;
  }
};

const saveState = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('state', serializedState);
  } catch (e) {
    // Ignore write errors;
  }
};

const peristedState = loadState();

store.subscribe(() => {
  saveState(store.getState());
});

const store = createStore(
  persistedState,
  // Others reducers...
);

render(
  <Provider store={store}>
    <App/>
  </Provider>,
  document.getElementById('root');
);

Serialization is an expensive operation. You should use a throttle function (like the one implemented by lodash) to limit the number of saves.

Eg:

import throttle from 'lodash/throttle';

store.subscribe(throttle(() => {
  saveState(store.getState());
}, 1000));

State lost after page reload. How to resolve this? · Issue #363 · rt2zz , OS: Windows 10 Pro redux-persist: "^4.8.0" So after a reload of any of my But I want the state, as of that moment in time, to remain intact after a page reload. ReactDOM.render(( <Provider store={store}> <Router> <App/>  OS: Windows 10 Pro redux-persist: "^4.8.0". So after a reload of any of my Router paths is made, state becomes === undefined. But I want the state, as of that moment in time, to remain intact after a page reload.

You can use something like redux-persist to save the redux state to local storage or to another storage system.

React Redux state is lost at page refresh - reactjs - html, in my react app I have 3 components. from the 1st component by a button, I use Link to go to the 2nd component. at the 2nd I create a state (redux store),  React monitors the state of its virtual DOM, updating components in the tree as necessary in response to changes of state. js and set the top of log the user in when they refresh so that they never get signed out of the chat With Redux, what we do is maintain the entire state of our application in a single object.

My personal advice for hot reloading is using this: React hot loader, this prevents page reload and only switch out the altered chunk. This implies that your state never gets lost while devving.

It is pretty easy to install. You only have to add an entry and wrap your initial component in hot which you can get from the package.

If you need more information on how it works i suggest watching this talk by the creator.

Is it normal that when page refreshes, redux state is gone?, https://github.com/rt2zz/redux-persist. If you are losing your state on a page redirect or traveling to a different route using react-router you will  Yichen Lu if you are not persisting the state then yes on a page refresh the state will return to the initial state whether that be {} or if you have specified an actual initialState. If you are wanting to persist your state I would recommend the following package:

Redux state is null on page reload, I have searched a lot for any solution. But couldn't figure out anything. I may be missing something in the redux flow. Tags:#reactjs#  Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.

Retaining React UI state without localStorage or redux-persist, How to retain filter data even after a page refresh? How this problem can be solved? window.localStorage. Before reload. There are two  Redux is a state container for JavaScript apps, often called a Redux store. It stores the whole state of the app in an immutable object tree. To create a store the createStore(reducer, [initialState], [enhancer]) function is used to create a new store.

React Redux - Persisting state through refreshes in React, In this episode I show you how to use localStorage to persist Redux state through a browser Duration: 6:51 Posted: Apr 7, 2018 In this episode I show you how to use localStorage to persist Redux state through a browser refresh or close event. If you want to support my React YouTube channel and get discounts on mentorship

Comments
  • It's natural...
  • @BhojendraRauniyar and the solution ?
  • save them in localstorage
  • isn't Thunk here as middleware to handle this? if I want to persist everything in local storage, why should I even use redux?
  • you may use redux-persist otherwise
  • This looks very convincing. so there is no need for thunk anymore?
  • and for seeing the state at chrome extention I should write composeWithDevTools(persistedState) ?
  • It doesn't change anything from your existing code. The second argument of createStore is simply the initialState. You still can add thunk and plug the chrome extension.
  • persistedState, should be placed as the enhancer? something like? createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)), persistedState );
  • Aha, I got it, Thanks a lot. best solution for my case :)