Created
March 30, 2020 23:34
-
-
Save ericelliott/0d3428142d1f106369c6d82210e3a2b9 to your computer and use it in GitHub Desktop.
A localStorage drop-in replacement for useState
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'; | |
const configureLocalStorage = key => initialValue => { | |
const [state, setState] = useState(() => { | |
try { | |
const value = localStorage.getItem(key); | |
return value ? JSON.parse(value) : initialValue; | |
} catch (e) { | |
console.log(e); | |
return initialValue; | |
} | |
}, initialValue); | |
const storeValue = value => { | |
const valueToStore = typeof value === 'function' ? value(state) : value; | |
try { | |
localStorage.setItem(key, JSON.stringify(valueToStore)); | |
} catch (err) { | |
console.log(err); | |
// This space intentionally left blank. | |
} | |
setState(valueToStore); | |
}; | |
return [state, storeValue]; | |
}; | |
export { configureLocalStorage }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment