Skip to content

Instantly share code, notes, and snippets.

@blacksmoke26
Created September 20, 2020 12:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blacksmoke26/af6c1b4c13cc99740285ab198d37fda4 to your computer and use it in GitHub Desktop.
Save blacksmoke26/af6c1b4c13cc99740285ab198d37fda4 to your computer and use it in GitHub Desktop.
React hook for Localforage (flow)
// @flow
// LocalForage: https://github.com/localForage/localForage
// npm i -S localForage
/**
* @author Junaid Atari <mj.atari@gmail.com>
* @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];
}
@blacksmoke26
Copy link
Author

I will check it! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment