Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux with router keep state when changing url

I have this issue:

I have a simple routing technique wrapped inside redux, like this:

<Provider store={store}>
    <Router>
      <React.Fragment>
        <Route exact path="/" component={App} />
        <Route path="/about" component={About} />
      </React.Fragment>
    </Router>
  </Provider>

And I have a simple Link in my App component like this

<Link to="/about">About</Link>

when I navigate to About by clicking the Link, everything is fine and my store is not reset, but here's the question: Is there any way to keep the state when I enter the URL in address bar manually or by refreshing the page (hitting F5)?

Thanks indeed!

like image 590
Amir Shahbabaie Avatar asked Nov 19 '25 10:11

Amir Shahbabaie


2 Answers

Redux store application will loose state as soon as you refresh the page:

If you want to store something which you want even after page refresh use local storage present in all browsers.

There is something called hot reloading in redux which will not loose data post refresh.

But with your current code store will reset, this is expected behavior.

like image 108
Anil Kumar Avatar answered Nov 20 '25 23:11

Anil Kumar


Although, local storage seems to be the solution, but if there is something you want on all the pages, you should dispatch action to get data in the App component in componentDidMount lifecycle hook.

App, being the most parent component, will set data into the redux store every time the page is loaded, and further routing will obviously not lead to loss of your data from redux.

This is a great solution for cases where you need to store information like 'profile info', that can be accessed on every page anytime.

like image 39
Abhishek Kumawat Avatar answered Nov 21 '25 00:11

Abhishek Kumawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!