Skip to content

Instantly share code, notes, and snippets.

@vuongngo
Created January 9, 2020 07:27
Show Gist options
  • Save vuongngo/b163fd2c9340556ceec619772742e06c to your computer and use it in GitHub Desktop.
Save vuongngo/b163fd2c9340556ceec619772742e06c to your computer and use it in GitHub Desktop.
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