alinea
Version:
Headless git-based CMS
37 lines (35 loc) • 960 B
JavaScript
import "../../chunks/chunk-NZLE2WMY.js";
// src/ui/hook/UseLocalStorage.ts
import { useEffect, useState } from "react";
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(initialValue);
const setValue = (value) => {
try {
setStoredValue(value);
if (typeof window !== "undefined")
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(error);
}
};
function initialize() {
try {
const item = window.localStorage.getItem(key);
setStoredValue(item ? JSON.parse(item) : initialValue);
} catch (error) {
console.error(error);
}
}
useEffect(() => {
initialize();
window.addEventListener("storage", (event) => {
if (event.storageArea === window.localStorage && event.key === key) {
initialize();
}
});
}, []);
return [storedValue, setValue];
}
export {
useLocalStorage
};