TinyBase logoTinyBase

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
TypeDescription
storeMergeableStore

The MergeableStore to synchronize.

channelNamestring

The name of the channel to use.

onSend?Send

An optional handler for the messages that this Synchronizer sends. This is suitable for debugging synchronization issues in a development environment, since v5.1.

onReceive?Receive

An optional handler for the messages that this Synchronizer receives. This is suitable for debugging synchronization issues in a development environment, since v5.1.

onIgnoredError?(error: any) => void

An optional handler for the errors that the Synchronizer would otherwise ignore when trying to synchronize data. This is suitable for debugging synchronization issues in a development environment.

returnsBroadcastChannelSynchronizer

A reference to the new BroadcastChannelSynchronizer object.

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