Skip to content

Commit 723f0e0

Browse files
committed
simplify storage
1 parent 77898b2 commit 723f0e0

File tree

1 file changed

+15
-30
lines changed

1 file changed

+15
-30
lines changed

src/storage.ts

Lines changed: 15 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,25 @@
11
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";
43

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 {
1714
return defaultValue;
1815
}
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;
2216
})();
2317

24-
// Create the signal once with the determined initial value.
25-
const [value, setValue] = createSignal<T>(initialValue);
18+
const [value, setValue] = createSignal<T>(initial);
2619

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+
});
3823

3924
return [value, setValue];
4025
}

0 commit comments

Comments
 (0)