Created
February 27, 2020 15:07
-
-
Save scorsi/587dd77b598c001e2657df9530660896 to your computer and use it in GitHub Desktop.
A hook useful to get/set data from/to localstorage
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 { useState } from 'react'; | |
export default (key, initialValue) => { | |
const [storedValue, setStoredValue] = useState(() => { | |
try { | |
const item = window.localStorage.getItem(key); | |
return item ? JSON.parse(item) : initialValue; | |
} catch (error) { | |
console.log(error); | |
return initialValue; | |
} | |
}); | |
const setValue = (value) => { | |
try { | |
const valueToStore = value instanceof Function ? value(storedValue) : value; | |
setStoredValue(valueToStore); | |
window.localStorage.setItem(key, JSON.stringify(valueToStore)); | |
} 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