Skip to content

Commit 3230ee6

Browse files
committed
fix: useLocalStorage not removing event listener
!nuf
1 parent d94d180 commit 3230ee6

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

frontend/src/ts/hooks/useLocalStorage.ts

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createSignal, createEffect, Accessor, Setter } from "solid-js";
1+
import { createSignal, Accessor, Setter, onCleanup } from "solid-js";
22
import { LocalStorageWithSchema } from "../utils/local-storage-with-schema";
33

44
export type UseLocalStorageOptions<T> = {
@@ -60,26 +60,21 @@ export function useLocalStorage<T>(
6060

6161
// Sync changes across tabs/windows
6262
if (syncAcrossTabs) {
63-
createEffect(() => {
64-
const handleStorageChange = (e: StorageEvent): void => {
65-
if (e.key === key && e.newValue !== null) {
66-
console.debug(`LS ${key} Storage event detected from another tab`);
67-
try {
68-
const parsed = schema.parse(JSON.parse(e.newValue));
69-
setValueInternal(() => parsed);
70-
} catch (error) {
71-
console.error(
72-
`LS ${key} Failed to parse storage event value`,
73-
error,
74-
);
75-
}
63+
const handleStorageChange = (e: StorageEvent): void => {
64+
if (e.key === key && e.newValue !== null) {
65+
console.debug(`LS ${key} Storage event detected from another tab`);
66+
try {
67+
const parsed = schema.parse(JSON.parse(e.newValue));
68+
setValueInternal(() => parsed);
69+
} catch (error) {
70+
console.error(`LS ${key} Failed to parse storage event value`, error);
7671
}
77-
};
72+
}
73+
};
7874

79-
window.addEventListener("storage", handleStorageChange);
80-
return () => {
81-
window.removeEventListener("storage", handleStorageChange);
82-
};
75+
window.addEventListener("storage", handleStorageChange);
76+
onCleanup(() => {
77+
window.removeEventListener("storage", handleStorageChange);
8378
});
8479
}
8580

0 commit comments

Comments
 (0)