-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseTabSharedState.ts
48 lines (39 loc) · 1.26 KB
/
useTabSharedState.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import * as React from "react";
export function deleteTabSharedState(name: string) {
// cleanup
}
// useTabSharedState
export function useTabSharedState<T>(
name: string,
initialValue: T
): [T, (updatedValue: T) => void] {
const [value, setInternalValue] = React.useState(initialValue);
const setValue = React.useCallback(
(newValue: T) => {
setInternalValue(newValue);
// set set remote
localStorage.setItem(name, JSON.stringify(newValue));
},
[name]
);
React.useEffect(() => {
const handleStorageChange = (event: StorageEvent) => {
// console.log(`Key Changed: ${event.key}`);
// console.log(`New Value: ${event.newValue}`);
// only if the right key changes, should we trigger our action
if (event.key === name) {
const valueFromLS = localStorage.getItem(name);
if (valueFromLS) {
const newValue = JSON.parse(valueFromLS);
setValue(newValue);
}
}
};
// this event will only trigger when a window other than itself makes changes to local storage
window.addEventListener("storage", handleStorageChange);
return () => {
window.removeEventListener("storage", handleStorageChange);
};
}, [name, setValue]);
return [value, setValue];
}