Created
January 9, 2020 07:27
-
-
Save vuongngo/b163fd2c9340556ceec619772742e06c 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
import localforage from 'localforage'; | |
const useStorage = (state, setState) => { | |
const [rehydrated, setRehydrated] = useState(false); | |
const [error, setError] = useState(null); | |
useEffect(() => { | |
// Async rehydration | |
localforage.getItem(config.key, (err, value) => { | |
if (err) { | |
setRehydrated(true); | |
return setError(err); | |
} | |
setState(rehydrated(value)); | |
setRehydrated(true); | |
}); | |
}, []); | |
useEffect(() => { | |
if (isNil(state) || isEmpty(state)) { | |
localforage.removeItem(config.key); | |
} | |
localforage.setItem(config.key, hydrate(state)); | |
}, [state]); | |
return { | |
rehydrated, | |
error, | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment