pashto-grammar/src/useStickyState.ts

23 lines
612 B
TypeScript
Raw Normal View History

2021-09-18 13:31:05 +00:00
import { useEffect, useState } from "react";
2021-11-04 00:09:42 +00:00
export default function useStickyState<T>(defaultValue: T, key: string): [
2021-09-18 22:22:47 +00:00
value: T,
setValue: React.Dispatch<React.SetStateAction<T>>,
2021-11-04 00:09:42 +00:00
] {
2021-09-18 22:22:47 +00:00
const [value, setValue] = useState<T>(() => {
const stickyValue = window.localStorage.getItem(key);
2021-09-18 23:23:41 +00:00
if (stickyValue === null) return defaultValue;
try {
return JSON.parse(stickyValue) as T;
} catch(e) {
console.error(e);
return defaultValue;
}
2021-09-18 22:22:47 +00:00
});
2021-09-18 13:31:05 +00:00
2021-09-18 22:22:47 +00:00
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
2021-09-18 13:31:05 +00:00
2021-11-04 00:09:42 +00:00
return [value, setValue];
2021-09-18 13:31:05 +00:00
}