Blog>
Snippets

State Synchronization Across Tabs Using Redux-Saga

Demonstrate a method to synchronize application state across multiple browser tabs using Redux-Saga to listen for storage events and dispatch actions to update the state accordingly.
function* syncStateSaga() {
  yield takeLatest('SYNC_STATE', function* (action) {
    const state = yield select();
    localStorage.setItem('appState', JSON.stringify(state));
  });
}
This saga listens for a 'SYNC_STATE' action and saves the current application state to localStorage, allowing it to be shared across tabs.
function* watchStorageEvents() {
  yield takeEvery('storage', function* (action) {
    if (action.key === 'appState') {
      const state = JSON.parse(action.newValue);
      yield put({ type: 'SET_STATE', payload: state });
    }
  });
}
This saga listens for storage events. If the 'appState' in localStorage is updated, it dispatches a 'SET_STATE' action to update the application state accordingly.
function setupStorageListener(dispatch) {
  window.addEventListener('storage', (event) => {
    if (event.key === 'appState') {
      dispatch({ type: 'storage', key: event.key, newValue: event.newValue });
    }
  });
}
This function sets up an event listener for the 'storage' event on the window object. When the 'storage' event fires, it dispatches an action that our saga can listen to.