Created
April 18, 2022 09:17
-
-
Save shettayyy/75a06b3da17ba0ebdc8f1c80d0ac1bcf to your computer and use it in GitHub Desktop.
A utility to store data locally on the web
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
const storage = () => { | |
const hasStorage = () => { | |
try { | |
const test = 'test' | |
localStorage.setItem(test, test) | |
localStorage.removeItem(test) | |
return true | |
} catch (e) { | |
return false | |
} | |
} | |
const set = (key: string, value: unknown) => { | |
if (hasStorage()) { | |
localStorage.setItem(key, JSON.stringify(value)) | |
} | |
} | |
const get = (key: string) => { | |
if (hasStorage()) { | |
const value = localStorage.getItem(key) | |
if (value) { | |
return JSON.parse(value) | |
} | |
} | |
return null | |
} | |
const remove = (key: string) => { | |
if (hasStorage()) { | |
localStorage.removeItem(key) | |
} | |
} | |
const clear = () => { | |
if (hasStorage()) { | |
localStorage.clear() | |
} | |
} | |
return { | |
hasStorage, | |
set, | |
get, | |
remove, | |
clear, | |
} | |
} | |
export default storage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment