Last active
January 8, 2021 13:25
-
-
Save YussufElarif/c30780ed3595695b7f73ea91db468159 to your computer and use it in GitHub Desktop.
React useStorage localStorage hook
This file contains 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
export function useStorage<T>(key: string) | |
{ | |
function getKey() | |
{ | |
const data = localStorage.getItem(key); | |
if (!data) | |
{ | |
return; | |
} | |
// "as T" used instead of "<T>". React throws a warning if "<T>" is used. | |
return JSON.parse(data) as T; | |
} | |
function setKey(body: T) | |
{ | |
localStorage.setItem(key, JSON.stringify(body)); | |
} | |
function deleteKey() | |
{ | |
localStorage.removeItem(key); | |
} | |
return { | |
getKey, | |
setKey, | |
deleteKey | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment