Skip to content

Commit eed3155

Browse files
authored
✨ feat: onBecomeMain callback (#10)
1 parent 329eb7d commit eed3155

File tree

5 files changed

+21
-4
lines changed

5 files changed

+21
-4
lines changed

README.md

+6
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,12 @@ Type: `boolean` (default: `false`)
156156

157157
If true, the store will only synchronize once with the main tab. After that, the store will be unsynchronized.
158158

159+
##### options.onBecomeMain
160+
161+
Type: `() => void`
162+
163+
A callback that will be called when the tab becomes the main tab.
164+
159165
### useBroadcast (hooks)
160166

161167
```ts

example/src/stores/useCountStore.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ export const useCountStore = create<CountStore>(
2020
mode: 'Sync',
2121
setMode: (mode) => set({ mode }),
2222
}),
23-
{ name: 'my-store' }
23+
{
24+
name: 'my-store',
25+
}
2426
)
2527
);

package-lock.json

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "use-broadcast-ts",
3-
"version": "1.4.5",
3+
"version": "1.5.0",
44
"description": "Use the Broadcast Channel API in React easily with hooks or Zustand, and Typescript!",
55
"type": "module",
66
"types": "./dist/index.d.ts",

src/shared.ts

+9
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ export type SharedOptions = {
1919
* @default false
2020
*/
2121
unsync?: boolean;
22+
23+
/**
24+
* Callback when this tab / window becomes the main tab / window
25+
*/
26+
onBecomeMain?: () => void;
2227
};
2328

2429
/**
@@ -240,6 +245,8 @@ const sharedImpl: SharedImpl = (f, options) => (set, get, store) => {
240245
if (e.data.id === id) {
241246
isMain = true;
242247
tabs.splice(0, tabs.length, ...e.data.tabs);
248+
249+
options?.onBecomeMain?.();
243250
}
244251
}
245252
};
@@ -257,6 +264,8 @@ const sharedImpl: SharedImpl = (f, options) => (set, get, store) => {
257264
if (!isSynced) {
258265
isMain = true;
259266
isSynced = true;
267+
268+
options?.onBecomeMain?.();
260269
}
261270
}, options?.mainTimeout ?? 100);
262271
};

0 commit comments

Comments
 (0)