diff options
author | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2022-06-03 19:04:53 +0300 |
---|---|---|
committer | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2022-06-03 19:04:53 +0300 |
commit | 0e7b36c2d443306325f17bb8850f5bb6176202bf (patch) | |
tree | 86629d4fe05d73f2d77dad423cc37d5a612430f3 /src/hooks/local.js | |
parent | 15d75cdc37e1459f7d11d004005d4305a6377ffd (diff) |
Diffstat (limited to 'src/hooks/local.js')
-rw-r--r-- | src/hooks/local.js | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/hooks/local.js b/src/hooks/local.js new file mode 100644 index 0000000..4b6b2ca --- /dev/null +++ b/src/hooks/local.js @@ -0,0 +1,31 @@ +import { useState } from "react"; + +const useLocalStorage = (key, initialValue) => { + const [storedValue, setStoredValue] = useState(() => { + if (typeof window === "undefined") { + return initialValue; + } + try { + const item = window.localStorage.getItem(key); + return item ? JSON.parse(item) : initialValue; + } catch (error) { + console.warn(error); + return initialValue; + } + }); + const setValue = (value) => { + try { + const valueToStore = + value instanceof Function ? value(storedValue) : value; + setStoredValue(valueToStore); + if (typeof window !== "undefined") { + window.localStorage.setItem(key, JSON.stringify(valueToStore)); + } + } catch (error) { + console.log(error); + } + }; + return [storedValue, setValue]; +} + +export default useLocalStorage; |