|
1 | | -import { createSignal, createEffect, Accessor, Setter } from "solid-js"; |
| 1 | +import { createSignal, Accessor, Setter, onCleanup } from "solid-js"; |
2 | 2 | import { LocalStorageWithSchema } from "../utils/local-storage-with-schema"; |
3 | 3 |
|
4 | 4 | export type UseLocalStorageOptions<T> = { |
@@ -60,26 +60,21 @@ export function useLocalStorage<T>( |
60 | 60 |
|
61 | 61 | // Sync changes across tabs/windows |
62 | 62 | 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); |
76 | 71 | } |
77 | | - }; |
| 72 | + } |
| 73 | + }; |
78 | 74 |
|
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); |
83 | 78 | }); |
84 | 79 | } |
85 | 80 |
|
|
0 commit comments