Reputation: 113
I have a page in my application that is an interactive chart with a bunch of settings (filters, time ranges, etc). I'd like to store them in-app state because some of the settings may be used by other components on another page, but right now if I click on any other tab and come back to the previous tab then the page shows the initial state(chart is gone, filtered data gone, date range showing the default value, dropdowns shows default ass well). And the state is also showing null
.
Upvotes: 11
Views: 20710
Reputation: 1095
Anything in your component state is dynamic; i.e., it is temporary. If you refresh the window, the old state is lost. A similar thing happens when you open a fresh tab—you get the state declared in your constructor. You can use any of the following if you want the state data in another tab:
Simply using redux won't solve your problem as redux store is also related to a specific browser tab. If you would like to persist your redux state across a browser refresh, it's best to do this using redux middleware. Check out the redux-persist, redux-storage middleware.
If you are using react-router
you can simply pass required state through the link when you open a fresh tab. Here's an example:
<Link to={{
pathname: '/pathname',
state: { message: 'hello, im a passed message!' }
}}/>
localStorage
and access localStorage
in other tabs.Upvotes: 18
Reputation: 1523
The straight forward solution to this is redux-state-sync. It will just work and the store will be updated on all tabs and even windows on the browser.
Upvotes: 1
Reputation: 18
I think you should implement react-redux into your app. React-redux is a state management tool that manage the state of your application at a centralized location and you access data from store at anytime from anywhere. React-redux: https://redux.js.org/basics/usage-with-react
Upvotes: -1
Reputation: 93
If you are looking to use a variable across the entire application you can also use localStorage
localStorage.setItem('move', this.state.move);
also don't forget to unset it when you are done!
localStorage.removeItem('move');
Upvotes: 4
Reputation: 1180
You some library for state management. The most popular one that's used with React is redux.
https://redux.js.org/introduction
Upvotes: -7