|
1 | 1 | import type { Accessor, Setter } from "solid-js"; |
2 | | -import { createSignal, createEffect, on } from "solid-js"; |
3 | | -import { isServer } from "solid-js/web"; |
| 2 | +import { createSignal, createEffect } from "solid-js"; |
4 | 3 |
|
5 | | -/** |
6 | | - * Creates a SolidJS signal that is automatically persisted to localStorage. |
7 | | - * |
8 | | - * @param key The key to use in localStorage. |
9 | | - * @param defaultValue The value to use if nothing is in storage. |
10 | | - * @returns A signal [getter, setter] pair. |
11 | | - */ |
12 | | -export function createStorageSignal<T>(key: string, defaultValue: T): [Accessor<T>, Setter<T>] { |
13 | | - // Determine the initial value based on the environment (server or client). |
14 | | - // This logic runs only once when the signal is created. |
15 | | - const initialValue = (() => { |
16 | | - if (isServer) { |
| 4 | +export function createStorageSignal<T>( |
| 5 | + key: string, |
| 6 | + defaultValue: T, |
| 7 | +): [Accessor<T>, Setter<T>] { |
| 8 | + const initial = ((): T => { |
| 9 | + const item = localStorage.getItem(key); |
| 10 | + if (!item) return defaultValue; |
| 11 | + try { |
| 12 | + return JSON.parse(item) as T; |
| 13 | + } catch { |
17 | 14 | return defaultValue; |
18 | 15 | } |
19 | | - // On the client, try to read the initial value from localStorage. |
20 | | - const storedValue = localStorage.getItem(key); |
21 | | - return storedValue ? JSON.parse(storedValue) : defaultValue; |
22 | 16 | })(); |
23 | 17 |
|
24 | | - // Create the signal once with the determined initial value. |
25 | | - const [value, setValue] = createSignal<T>(initialValue); |
| 18 | + const [value, setValue] = createSignal<T>(initial); |
26 | 19 |
|
27 | | - // This effect runs only on the client because localStorage is client-side. |
28 | | - // It also ensures the value is saved whenever it changes. |
29 | | - // Use an if statement for conditional execution to satisfy the linter. |
30 | | - if (!isServer) { |
31 | | - createEffect( |
32 | | - on(value, () => { |
33 | | - // It writes the new value back to localStorage. |
34 | | - localStorage.setItem(key, JSON.stringify(value())); |
35 | | - }) |
36 | | - ); |
37 | | - } |
| 20 | + createEffect(() => { |
| 21 | + localStorage.setItem(key, JSON.stringify(value())); |
| 22 | + }); |
38 | 23 |
|
39 | 24 | return [value, setValue]; |
40 | 25 | } |
0 commit comments