feat: folding options (#459)

* feat: folding options

* chore: update

* chore: update

Co-authored-by: boojack <stevenlgtm@gmail.com>
This commit is contained in:
Stephen Zhou
2022-11-14 22:06:05 +08:00
committed by GitHub
parent da80d4ef62
commit 3775d5c9c2
7 changed files with 54 additions and 2 deletions

View File

@ -0,0 +1,26 @@
import { useState } from "react";
const useLocalStorage = <T>(key: string, initialValue: T) => {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value: T | ((val: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue] as const;
};
export default useLocalStorage;