Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we use the same state across multiple tabs (pages)?

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.

like image 370
Khal Drogo Avatar asked Mar 20 '18 12:03

Khal Drogo


People also ask

How do you syncing React state across multiple tabs with redux?

import React from "react"; import ReactDOM from "react-dom"; import { Provider, connect } from "react-redux"; import { createStore, applyMiddleware } from "redux"; import { createStateSyncMiddleware, initMessageListener, } from "redux-state-sync"; const Form = ({ name, handleChange }) => { return ( <> <input value={ ...

Is React state shared between tabs?

In the case of applications developed in ReactJS that work with state control using useState and useContext hooks, or even Redux in more complex scenarios, by default, the context is kept separately for each active tab in the user's browser.

Is redux state shared across tabs?

Redux is not shared across multiple tabs.

How do I share a state between components in React?

In React, sharing state is accomplished by moving it up to the closest common ancestor of the components that need it. This is called “lifting state up”. We will remove the local state from the TemperatureInput and move it into the Calculator instead.


1 Answers

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:

  1. 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.

  2. 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!' } 
}}/>
  1. Simply store the data in localStorage and access localStorage in other tabs.
like image 129
Ayesha Mundu Avatar answered Oct 16 '22 06:10

Ayesha Mundu