createBroadcastChannelSynchronizer
The createBroadcastChannelSynchronizer
function creates a BroadcastChannelSynchronizer
object that can synchronize MergeableStore
data to and from other MergeableStore
instances via a browser's BroadcastChannel API.
createBroadcastChannelSynchronizer(
store: MergeableStore,
channelName: string,
onSend?: Send,
onReceive?: Receive,
onIgnoredError?: (error: any) => void,
): BroadcastChannelSynchronizer
Type | Description | |
---|---|---|
store | MergeableStore | The |
channelName | string | The name of the channel to use. |
onSend? | Send | An optional handler for the messages that this |
onReceive? | Receive | An optional handler for the messages that this |
onIgnoredError? | (error: any) => void | An optional handler for the errors that the |
returns | BroadcastChannelSynchronizer | A reference to the new |
As well as providing a reference to the MergeableStore
to persist, you must provide a channel name, used by all the browser tabs, workers, or contexts that need to synchronize together.
A final set of optional handlers can be provided to help debug sends, receives, and errors respectively.
Example
This example creates two BroadcastChannelSynchronizer
objects to synchronize one MergeableStore
to another.
import {createBroadcastChannelSynchronizer} from 'tinybase/synchronizers/synchronizer-broadcast-channel';
import {createMergeableStore} from 'tinybase';
const store1 = createMergeableStore();
const store2 = createMergeableStore();
const synchronizer1 = createBroadcastChannelSynchronizer(
store1,
'channelA',
);
const synchronizer2 = createBroadcastChannelSynchronizer(
store2,
'channelA',
);
await synchronizer1.startSync();
await synchronizer2.startSync();
store1.setTables({pets: {fido: {species: 'dog'}}});
store2.setTables({pets: {felix: {species: 'cat'}}});
// ...
console.log(store1.getTables());
// -> {pets: {fido: {species: 'dog'}, felix: {species: 'cat'}}}
console.log(store2.getTables());
// -> {pets: {fido: {species: 'dog'}, felix: {species: 'cat'}}}
synchronizer1.destroy();
synchronizer2.destroy();
Since
v5.0.0