Created
March 8, 2019 05:13
-
-
Save enjoylife/cfdd2cceeda0ff5098cea57d81a8d9d0 to your computer and use it in GitHub Desktop.
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
// @flow | |
import {useState, useEffect} from 'react'; | |
// Hook | |
export default function useLocalStorage(key, initialValue) { | |
// State to store our value | |
// Pass initial state function to useState so logic is only executed once | |
const [storedValue, setStoredValue] = useState(() => { | |
try { | |
// Get from local storage by key | |
if (__BROWSER__) { | |
const item = window.localStorage.getItem(key); | |
// Parse stored json or if none return initialValue | |
return item ? JSON.parse(item) : initialValue; | |
} else { | |
return initialValue; | |
} | |
} catch (error) { | |
// eslint-disable-next-line no-console | |
console.error(error); | |
return initialValue; | |
} | |
}); | |
useEffect(() => { | |
// eslint-disable-next-line no-console | |
__DEV__ && console.log(`[localstorage] - ${key}`, storedValue); | |
try { | |
if (__BROWSER__) { | |
window.localStorage.setItem(key, JSON.stringify(storedValue)); | |
} | |
} catch (error) { | |
// eslint-disable-next-line no-console | |
console.error(error); | |
} | |
}, [key, storedValue]); | |
return [storedValue, setStoredValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment