You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
31 lines
846 B
31 lines
846 B
import {Dispatch, SetStateAction, useEffect, useState} from "react";
|
|
|
|
function loadData<T>(key: string, defValue: T): T {
|
|
const newData = window.localStorage.getItem(`ykonsole2.${key}`);
|
|
if (newData === null) {
|
|
return defValue;
|
|
}
|
|
|
|
return JSON.parse(newData) as T;
|
|
}
|
|
|
|
export default function useLocalStorage<T>(key: string, defValue: T): [T, Dispatch<SetStateAction<T>>] {
|
|
const [data, setData] = useState(() => loadData(key, defValue));
|
|
|
|
useEffect(() => {
|
|
window.localStorage.setItem(`ykonsole2.${key}`, JSON.stringify(data));
|
|
}, [key, data]);
|
|
|
|
useEffect(() => {
|
|
const callback = () => {
|
|
setData(loadData(key, defValue));
|
|
};
|
|
|
|
window.addEventListener("storage", callback);
|
|
return () => {
|
|
window.removeEventListener("storage", callback);
|
|
};
|
|
}, [key, defValue]);
|
|
|
|
return [data, setData];
|
|
}
|