Created
January 11, 2024 21:26
-
-
Save GalindoSVQ/07cbc6330876c8aa941c0da3b293d83a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react"; | |
const dispatchStorageEvent = (key, newValue) => { | |
window.dispatchEvent(new StorageEvent("storage", { key, newValue })); | |
}; | |
const setItem = (key, value) => { | |
const stringifiedValue = JSON.stringify(value); | |
window.localStorage.setItem(key, stringifiedValue); | |
dispatchStorageEvent(key, stringifiedValue); | |
}; | |
const removeItem = (key) => { | |
window.localStorage.removeItem(key); | |
dispatchStorageEvent(key, null); | |
}; | |
const getItem = (key) => { | |
return window.localStorage.getItem(key); | |
}; | |
const subscribe = (callback) => { | |
window.addEventListener("storage", callback); | |
return () => window.removeEventListener("storage", callback); | |
}; | |
const getServerSnapshot = () => { | |
throw Error("useLocalStorage is a client-only hook"); | |
}; | |
export default function useLocalStorage(key, initialValue) { | |
const getSnapshot = () => getItem(key); | |
const store = React.useSyncExternalStore( | |
subscribe, | |
getSnapshot, | |
getServerSnapshot | |
); | |
const setState = React.useCallback( | |
(v) => { | |
try { | |
const nextState = typeof v === "function" ? v(JSON.parse(store)) : v; | |
if (nextState === undefined || nextState === null) { | |
removeItem(key); | |
} else { | |
setItem(key, nextState); | |
} | |
} catch (e) { | |
console.warn(e); | |
} | |
}, | |
[key, store] | |
); | |
React.useEffect(() => { | |
if (getItem(key) === null && typeof initialValue !== "undefined") { | |
setItem(key, initialValue); | |
} | |
}, [key, initialValue]); | |
return [store ? JSON.parse(store) : initialValue, setState]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackblitz.com/edit/stackblitz-starters-dpb4xy?file=src%2FApp.tsx