|
| 1 | +import type { Accessor, Setter } from "solid-js"; |
| 2 | +import { createSignal, createEffect, on } from "solid-js"; |
| 3 | +import { isServer } from "solid-js/web"; |
| 4 | + |
| 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) { |
| 17 | + return defaultValue; |
| 18 | + } |
| 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 | + })(); |
| 23 | + |
| 24 | + // Create the signal once with the determined initial value. |
| 25 | + const [value, setValue] = createSignal<T>(initialValue); |
| 26 | + |
| 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 | + } |
| 38 | + |
| 39 | + return [value, setValue]; |
| 40 | +} |
0 commit comments