Skip to content

@statesync/persistence


@statesync/persistence / withCrossTabSync

Function: withCrossTabSync()

ts
function withCrossTabSync<T>(storage, options): object;

Defined in: persistence/src/cross-tab.ts:335

Wraps a storage backend's save method to automatically broadcast snapshots to other tabs after each successful save.

This is a lower-level utility for cases where you want cross-tab sync without using the full createPersistenceApplier. The returned object exposes both the wrapped save function and the underlying CrossTabSync instance for manual control.

Type Parameters

Type ParameterDescription
TThe shape of the application state.

Parameters

ParameterTypeDescription
storage{ save: Promise<void>; }Any object with a save method (typically a StorageBackend).
storage.save-
optionsCrossTabSyncHandlers<T>Cross-tab sync configuration and event handlers.

Returns

object

An object with a save method (broadcasts after writing) and a crossTab property for direct access to the sync manager.

crossTab

ts
crossTab: CrossTabSync<T>;

save()

ts
save(snapshot): Promise<void>;

Parameters

ParameterType
snapshotSnapshotEnvelope<T>

Returns

Promise<void>

Example

typescript
const { save, crossTab } = withCrossTabSync(
  createLocalStorageBackend({ key: 'my-state' }),
  {
    channelName: 'my-app-state',
    onSnapshot: (snapshot) => applier.apply(snapshot),
  },
);

await save(snapshot); // Saves to storage AND broadcasts to other tabs
crossTab.dispose();   // Cleanup when done

Released under the MIT License.