MCPcopy Create free account
hub / github.com/hashintel/hash / useStorageSync

Function useStorageSync

apps/plugin-browser/src/pages/shared/use-storage-sync.ts:25–87  ·  view source on GitHub ↗
(
  key: Key,
  initialValue: NonUndefined<LocalStorage[Key]>,
)

Source from the content-addressed store, hash-verified

23 * @see https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage
24 */
25export const useStorageSync = <Key extends keyof LocalStorage>(
26 key: Key,
27 initialValue: NonUndefined<LocalStorage[Key]>,
28) => {
29 const [stateValue, setStateValue] = useState<LocalStorage[Key]>(initialValue);
30 const [storageChecked, setStorageChecked] = useState(false);
31
32 useEffect(() => {
33 if (storageChecked) {
34 return;
35 }
36
37 const getStorageValue = async () => {
38 const storageValue = await getFromLocalStorage(key);
39
40 if (typeof storageValue !== "undefined") {
41 setStateValue(storageValue);
42 } else {
43 setStateValue(initialValue);
44 }
45
46 setStorageChecked(true);
47 };
48
49 void getStorageValue();
50 }, [initialValue, key, storageChecked]);
51
52 useEffect(() => {
53 const listener = (
54 changes: Record<string, browser.Storage.StorageChange>,
55 areaName: string,
56 ) => {
57 if (
58 areaName === "local" &&
59 key in changes &&
60 changes[key] &&
61 changes[key].newValue !== stateValue
62 ) {
63 setStateValue(changes[key].newValue as LocalStorage[Key]);
64 }
65 };
66
67 // Listen to changes in the storage area in case it's updated from another component, window, or background script
68 browser.storage.onChanged.addListener(listener);
69
70 return () => {
71 browser.storage.onChanged.removeListener(listener);
72 };
73 }, [key, stateValue]);
74
75 const setValue = useCallback(
76 (newValue: LocalStorage[Key]) => {
77 setStateValue(newValue);
78 void setInLocalStorage(key, newValue);
79 },
80 [key],
81 );
82

Callers 9

useUserValueFunction · 0.90
useEntityTypesFunction · 0.90
PopupFunction · 0.90
ActionCenterFunction · 0.90
InferEntitiesActionFunction · 0.90
QuickNoteActionFunction · 0.90
useFlowRunsFunction · 0.90
HistoryRowFunction · 0.90

Calls 2

setInLocalStorageFunction · 0.90
getStorageValueFunction · 0.85

Tested by

no test coverage detected