Skip to content

Instantly share code, notes, and snippets.

@shettayyy
Created April 18, 2022 09:17
Show Gist options
  • Save shettayyy/75a06b3da17ba0ebdc8f1c80d0ac1bcf to your computer and use it in GitHub Desktop.
Save shettayyy/75a06b3da17ba0ebdc8f1c80d0ac1bcf to your computer and use it in GitHub Desktop.
A utility to store data locally on the web
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