Skip to content

Instantly share code, notes, and snippets.

@vuongngo
Created January 9, 2020 07:30
Show Gist options
  • Save vuongngo/0e15f197d76a6c6c26c644c940d3b95e to your computer and use it in GitHub Desktop.
Save vuongngo/0e15f197d76a6c6c26c644c940d3b95e to your computer and use it in GitHub Desktop.
const merge = (initialValue, hydratedValue) => {
if (!isObjectLike(initialValue)) {
return initialValue;
}
return {...hydratedValue, ...initialValue};
};
const useStorage = (state, setState, initialValue) => {
const [rehydrated, setRehydrated] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
localforage.getItem(config.key, (err, value) => {
if (err) {
setRehydrated(true);
return setError(err);
}
// Merge initialValue with persist value
let mergedValue = rehydrated(value);
if (initialValue) {
mergedValue = merge(initialValue, mergedValue);
}
setState(mergedValue);
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