Skip to main content

Sync State

npm GitHub GitHub Repo stars

Syncs elf store state across tabs

The syncState() function gives you the ability to synchronize an elf store state across multiple tabs, windows or iframes using the Broadcast Channel API.

First, you need to install the package via npm:

npm i elf-sync-state

To use it you should call the syncState() function passing the store:

import { createStore, withProps } from '@ngneat/elf';
import { syncState } from 'elf-sync-state';

interface AuthProps {
user: { id: string } | null;
token: string | null;
}

const authStore = createStore(
{ name: 'auth' },
withProps<AuthProps>({ user: null, token: null })
);

syncState(authStore);

As the second parameter you can pass an optional Options object, which can be used to define the following:

  • channel: the name of the channel (by default - the store name plus a @store suffix).
  • source: a function that receives the store and return what to sync from it. The default is (store) => store.
  • preUpdate: a function to map the event message and get the data. The default is (event) => event.data.
  • runGuard: a function that returns whether the actual implementation should be run. The default is () => typeof window !== 'undefined' && typeof window.BroadcastChannel !== 'undefined'.
import { syncState } from 'elf-sync-state';
import { authStore } from './auth.store';

syncState(authStore, { channel: 'auth-channel' });

The sync state also returns the BroadcastChannel object created or undefined if the runGuard function returns false.

import { syncState } from 'elf-sync-state';
import { authStore } from './auth.store';

const channel: BroadcastChannel | undefined = syncState(authStore);

Sync a subset of the state

The includeKeys() operator can be used to sync a subset of the state:

import { includeKeys, syncState } from 'elf-sync-state';
import { authStore } from './auth.store';

syncState(authStore, {
source: (store) => store.pipe(includeKeys(['user'])),
});

Pre Update interceptor

The preUpdate option can be used to intercept the MessageEvent and modify the data to be synchronized taking into account other properties of the event.

import { includeKeys, syncState } from 'elf-sync-state';
import { authStore } from './auth.store';

syncState(authStore, {
preUpdate: (event) => {
console.log(event);
return event.origin === '' ? undefined : event.data;
},
});

Integration with Elf

The use of this library has been tested together with other Elf libraries, such as elf-entities, elf-persist-state or elf-state-history. I have also tried to be consistent with their programming style and documentation to help with integration.

Here you can see an example of using all of these in an Angular application. Just open the result in two different tabs to see the library in action.

⚠️ There may be a desync due to hot reload