Created
September 20, 2020 12:54
-
-
Save blacksmoke26/af6c1b4c13cc99740285ab198d37fda4 to your computer and use it in GitHub Desktop.
React hook for Localforage (flow)
This file contains hidden or 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 | |
// LocalForage: https://github.com/localForage/localForage | |
// npm i -S localForage | |
/** | |
* @author Junaid Atari <[email protected]> | |
* @link https://github.com/blacksmoke26 | |
* @since 2020-08-05 | |
*/ | |
import React from 'react'; | |
import localforage from 'localforage'; | |
type HookMethods = [ | |
any, | |
( value: any ) => void, | |
() => void, | |
]; | |
/** | |
* React custom hook to save/restore value from localStorage using localforage library | |
* @example | |
* ```js | |
* function App() { | |
* const [value, set, remove] = useLocalForge('my-key', {}); | |
* } | |
* ``` | |
*/ | |
export default function useLocalForge ( key: string, initialValue?: any ): HookMethods { | |
const [storedValue, setStoredValue] = React.useState(initialValue); | |
React.useEffect(() => { | |
(async function () { | |
try { | |
const value = await localforage.getItem(key); | |
setStoredValue(value); | |
} catch ( err ) { | |
return initialValue; | |
} | |
})(); | |
}, [initialValue, storedValue, key]); | |
/** Set value */ | |
const set = ( value: any ) => { | |
(async function () { | |
try { | |
await localforage.setItem(key, value); | |
setStoredValue(value); | |
} catch (err) { | |
return initialValue; | |
} | |
})(); | |
}; | |
/** Removes value from local storage */ | |
const remove = () => { | |
(async function () { | |
try { | |
await localforage.removeItem(key); | |
setStoredValue(null); | |
} catch (e) {} | |
})(); | |
}; | |
return [storedValue, set, remove]; | |
} |
It seems that if storedValue
is an object, this causes a render loop since storedValue
is a dependency of the useEffect
hook.
I will check it! Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Vanilla JS version: