Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle separate state for each browser tab in reactjs?

We are opening new window tab which contains the userList based on the selected userId from a list. I open the new window like this:

this.props.getVisitDetails(this.props.userId)
var win = window.open('./requisition','_blank');
win.onload = function() { this.document.title = windowTittle; }
win.focus();
this.state.oldWindow.push(win);

Here I am getting userId from the Redux store. The problem is that if I am opening more than one window tab then userId on every window tab will have the same userId and when you will click refresh then all window tabs will have the same data. So my question is how can I maintain a separate state for each window tab?

Note: all browser tab all sharing same stored state that we saved using createstore method,so in my case visitid will be updated on every row click which will open browser's new tab. This is how the data is "shared"

like image 511
Gorakh Nath Avatar asked Jan 19 '17 15:01

Gorakh Nath


People also ask

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.

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

To sync it across tabs, add the Redux State Sync middleware and setup a message listener. import {createStore, applyMiddleware} from "redux"; import {createStateSyncMiddleware, initMessageListener} from "redux-state-sync"; const reduxStateSyncConfig = {}; const reducer = (state, action) => ({...

Is redux state shared across tabs?

Redux-State-Sync 3. A lightweight middleware to sync your redux state across browser tabs. It will listen to the Broadcast Channel and dispatch exactly the same actions dispatched in other tabs to keep the redux state in sync.

How do you manage state in ReactJS?

Local state is most often managed in React using the useState hook. For example, local state would be needed to show or hide a modal component or to track values for a form component, such as form submission, when the form is disabled and the values of a form's inputs.


1 Answers

Your store is not shared across multiple tabs, So every time you open new tab your whole application gets loaded again along with initialization of fresh store. So, In your case simple solution will be to open new tab with URL containing userId as query param(window.open('./requisition?userId=${userId}','_blank');). Such that you will be able to maintain separate userId in different browser tabs.

like image 129
Vivek Sanjay Tikar Avatar answered Nov 11 '22 21:11

Vivek Sanjay Tikar