vue.joedoe.dev

← Totes les receptesComposables

Un ref que es desa sol

Preferències, esborranys, l'últim filtre… Aguanta recàrregues, se sincronitza entre pestanyes i no trenca el render al servidor.

TypeScript
import { onMounted, onUnmounted, ref, watch, type Ref } from "vue";

/**
 * A ref that lives in localStorage: survives reloads and stays in sync
 * between tabs. Reads after mount, so server rendering never touches it.
 */
export function useLocalStorage<T>(key: string, initial: T): Ref<T> {
	const value = ref(initial) as Ref<T>;

	const read = () => {
		try {
			const saved = localStorage.getItem(key);
			if (saved !== null) value.value = JSON.parse(saved);
		} catch {
			/* Private mode or broken JSON: keep the initial value. */
		}
	};

	const onStorage = (event: StorageEvent) => {
		if (event.key === key) read();
	};

	onMounted(() => {
		read();
		window.addEventListener("storage", onStorage);
	});
	onUnmounted(() => window.removeEventListener("storage", onStorage));

	watch(
		value,
		(next) => {
			try {
				localStorage.setItem(key, JSON.stringify(next));
			} catch {
				/* Full or blocked: the ref still works for this visit. */
			}
		},
		{ deep: true },
	);

	return value;
}

↑↓ moure's · ↵ obrir · esc tancar