use-broadcast-ts
Version:
Use the Broadcast Channel API in React easily with hooks or Zustand, and Typescript!
68 lines (67 loc) • 2.25 kB
TypeScript
import { StateCreator, StoreMutatorIdentifier } from 'zustand';
export type SharedOptions<T = unknown> = {
/**
* The name of the broadcast channel
* It must be unique
*/
name?: string;
/**
* Main timeout
* If the main tab / window doesn't respond in this time, this tab / window will become the main
* @default 100 ms
*/
mainTimeout?: number;
/**
* If true, the store will only synchronize once with the main tab. After that, the store will be unsynchronized.
* @default false
*/
unsync?: boolean;
/**
* If true, will not serialize with JSON.parse(JSON.stringify(state)) the state before sending it.
* This results in a performance boost, but it is on the user to ensure there are no unsupported types in their state.
* @default false
*/
skipSerialization?: boolean;
/**
* Custom function to parse the state before sending it to the other tabs
* @param state The state
* @returns The parsed state
*/
partialize?: (state: T) => Partial<T>;
/**
* Custom function to merge the state after receiving it from the other tabs
* @param state The current state
* @param receivedState The state received from the other tab
* @returns The restored state
*/
merge?: (state: T, receivedState: Partial<T>) => T;
/**
* Callback when this tab / window becomes the main tab / window
* Triggered only in the main tab / window
*/
onBecomeMain?: (id: number) => void;
/**
* Callback when a new tab is opened / closed
* Triggered only in the main tab / window
*/
onTabsChange?: (ids: number[]) => void;
};
/**
* The Shared type
*/
export type Shared = <T extends object, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = []>(f: StateCreator<T, Mps, Mcs>, options?: SharedOptions<T>) => StateCreator<T, Mps, Mcs>;
/**
* Shared middleware
*
* @example
* import { create } from 'zustand';
* import { shared } from 'use-broadcast-ts';
*
* const useStore = create(
* shared(
* (set) => ({ count: 0 }),
* { name: 'my-store' }
* )
* );
*/
export declare const shared: Shared;