Created
November 25, 2019 15:13
-
-
Save aapzu/5d09d53cb8dab37cb95be7fdc50d750e to your computer and use it in GitHub Desktop.
useLocalStorage.ts
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
import { useState } from "react" | |
// tslint:disable-next-line:no-any | |
export const useLocalStorage = <T extends any>(key: string, initialValue: T) => { | |
const [storedValue, setStoredValue] = useState<T>(() => { | |
try { | |
// Get from local storage by key | |
const item = window.localStorage.getItem(key) | |
// Parse stored json or if none return initialValue | |
return item ? JSON.parse(item) : initialValue | |
} catch (error) { | |
// If error also return initialValue | |
console.log(error) | |
return initialValue | |
} | |
}) | |
const setValue = (value: T) => { | |
try { | |
setStoredValue(value) | |
window.localStorage.setItem(key, JSON.stringify(value)) | |
} catch (error) { | |
console.log(error) | |
} | |
} | |
return [storedValue, setValue] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment