Fork of atp.tools as a universal profile for people on the ATmosphere
1import { useEffect, useState } from "preact/hooks";
2import type { Dispatch, StateUpdater } from "preact/hooks";
3
4/**
5 * Sets a value in localStorage with JSON stringification
6 */
7export function setToLocalStorage<T>(key: string, value: T): void {
8 try {
9 localStorage.setItem(key, JSON.stringify(value));
10 } catch (error) {
11 console.error(`Error saving to localStorage (${key}):`, error);
12 }
13}
14
15/**
16 * Gets a value from localStorage with JSON parsing
17 */
18export function getFromLocalStorage<T>(key: string, defaultValue: T): T {
19 try {
20 const item = localStorage.getItem(key);
21
22 if (item === null) {
23 setToLocalStorage(key, defaultValue);
24 return defaultValue;
25 }
26
27 return JSON.parse(item) as T;
28 } catch (error) {
29 console.error(`Error reading from localStorage (${key}):`, error);
30 return defaultValue;
31 }
32}
33
34/**
35 * Custom hook that syncs state with localStorage
36 */
37export function useStoredState<T>(
38 key: string,
39 defaultValue: T,
40): [T, Dispatch<StateUpdater<T>>] {
41 const [value, setValue] = useState<T>(() =>
42 getFromLocalStorage(key, defaultValue),
43 );
44
45 useEffect(() => {
46 console.log("useStoredState", key, value);
47 setToLocalStorage(key, value);
48 }, [key, value]);
49
50 return [value, setValue];
51}