Skip to content

Commit

Permalink
feat(useSyncWithLS): disable callback in active tab
Browse files Browse the repository at this point in the history
  • Loading branch information
iapolya committed Mar 22, 2024
1 parent 7a93a52 commit 55bdbfa
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
11 changes: 6 additions & 5 deletions src/components/Stories/hooks/useSyncWithLS/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ The `useSyncWithLS` hook executes callback when value changed in Local Storage

## Properties

| Name | Description | Type | Default |
| :------------- | :----------------------------------------------------------- | :------------: | :---------: |
| callback | Callback function called when key in local storage triggered | `VoidFunction` | |
| dataSourceName | Name for data source of keys | `string` | 'sync-tabs' |
| uniqueKey | Key in local storage for handle | `string` | |
| Name | Description | Type | Default |
| :----------------------- | :----------------------------------------------------------- | :------------: | :---------: |
| callback | Callback function called when key in local storage triggered | `VoidFunction` | |
| dataSourceName | Name for data source of keys | `string` | 'sync-tabs' |
| uniqueKey | Key in local storage for handle | `string` | |
| disableActiveTabCallback | Disable callback in tab that triggers local storage | `boolean` | 'false' |
8 changes: 7 additions & 1 deletion src/components/Stories/hooks/useSyncWithLS/useSyncWithLS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ export type UseSyncWithLSInputProps<T> = {
callback: T;
uniqueKey: string;
dataSourceName?: string;
disableActiveTabCallback?: boolean;
};
export type UseSyncWithLSOutputProps = {callback: (...args: unknown[]) => void};

export const useSyncWithLS = <T extends Function>({
dataSourceName = 'sync-tabs',
callback,
uniqueKey,
disableActiveTabCallback = false,
}: UseSyncWithLSInputProps<T>): UseSyncWithLSOutputProps => {
const key = `${dataSourceName}.${uniqueKey}`;

Expand All @@ -34,7 +36,11 @@ export const useSyncWithLS = <T extends Function>({
return {
callback: React.useCallback(() => {
localStorage.setItem(key, String(Number(localStorage.getItem(key) || '0') + 1));

if (disableActiveTabCallback) {
return undefined;
}
return callback();
}, [key, callback]),
}, [key, disableActiveTabCallback, callback]),
};
};

0 comments on commit 55bdbfa

Please sign in to comment.