NPM doesn't let me use the name uselocalforage
because there is a similar named, abandoned, package use-localforage
, this package is currently published under the name of @vicary/uselocalforage
.
Installation
npm install @vicary/uselocalforage
Usage
Step 1. Add the provider in your app.
import React from "react";
import App from "./App";
import { LocalForageProvider } from "@vicary/uselocalforage";
export default () => (
<LocalForageProvider>
<App />
</LocalForageProvider>
);
Step 2. Use the hook
useLocalForage
It has a similar API as react-use#useLocalStorage
and useState
, intentionally simplifies the API for ease of use.
import { useLocalForage } from "@vicary/uselocalforage";
const PageComponent = () => {
const [user, setUser] = useLocalForage("user", { guest: true });
return <>Current user: {user.guest ? "guest" : user.id}</>;
};
This hook does not manage the loading state so it expects
useLocalStorageAsync
Because of the asynchronous behavior of localforage, returned value will fallback to defaultValue
before the promise is resolved.
If the application requires explicit knowledge of the loading state, there is a third item in the returned array as a boolean to indicate a loading state.
const {
value, // The current value
setValue, // Value setter
loading, // Loading status, true if the localforage.getItem promise is resolving.
remove, // Deletes the key from storage, value will fallback to default.
} = useLocalForage("user", { guest: true });