streamich / react-use

React Hooks — 👍
http://streamich.github.io/react-use
The Unlicense
41.86k stars 3.16k forks source link

New hook for `LocalForge` library! #1522

Open blacksmoke26 opened 4 years ago

blacksmoke26 commented 4 years ago

I have written a hook for my app. If it's useful, you can use it:

// LocalForage: https://github.com/localForage/localForage
// npm i -S localForage

Source:

/**
 * @author Junaid Atari <mj.atari@gmail.com>
 * @link https://github.com/blacksmoke26
 * @since 2020-08-05
 */

import React from 'react';
import localforage from 'localforage';

/**
 * React custom hook to save/restore value from localStorage using localforage library
 * @example
 * ```js
 * function App() {
 *  const [value, set, remove] = useLocalForge('my-key', {});
 * }
 * ```
 * @param {string} key - Unique storage key
 * @param {*} initialValue=null - Initial value
 * @returns {[any, (function(any): void), (function(): void)]}
 */
export default function useLocalForge ( key, initialValue = null ) {
    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 ) => {
        (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];
}
ngobach commented 4 years ago

Hi,

Again, you might want to make a PR instead of creating issues to share your pratices. And how about extending useLocalStorage hook to make it accept an alternative localStorage implementation? So users can pass in localForage as a hook parameter. It will help providing consistent API with useLocalStorage hook instead of providing your own one.

blacksmoke26 commented 4 years ago

Natively, both fill the same hole, but Localforge take care of browsers with ease.

You have a point, i will dig into it and get back to you

dzcpy commented 3 years ago

localForage*