use-db-storage
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

use-db-storage

IndexedDB React hook that mimics useState API supporting optimistic updates

Gzipped Size Build Status

Install

npm install use-db-storage

Usage

import useDbStorage from 'use-db-storage'

export default function Todos() {
    const [todos, setTodos] = useDbStorage('todos', {
        defaultValue: ['buy avocado', 'do 50 push-ups']
    })
}

API

useDbStorage(key: string, options?: StorageStateOptions)

Returns [value, setValue, removeItem] when called. The first two values are the same as useState(). The third value calls IDBObjectStore.delete() and removes the data from the db.

key

Type: string

The key used when calling localStorage.setItem(key) and localStorage.getItem(key).

⚠️ Be careful with name conflicts as it is possible to access a property which is already in localStorage that was created from another place in the codebase or in an old version of the application.

options.defaultValue

Type: any

Default: undefined

The default value. You can think of it as the same as useState(defaultValue).

options.optimistic

Type: boolean

Default: true

IndexedDB is async. When optimistic is enabled, calling setState will synchronously/immediately update the state and it will roll back the state if adding the data to the database fails. You can disable by setting optimistic: false.

Related

/use-db-storage/

    Package Sidebar

    Install

    npm i use-db-storage

    Weekly Downloads

    3

    Version

    0.2.0

    License

    MIT

    Unpacked Size

    8.67 kB

    Total Files

    6

    Last publish

    Collaborators

    • astoilkov