Created
January 9, 2020 07:30
-
-
Save vuongngo/0e15f197d76a6c6c26c644c940d3b95e 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
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