Skip to content

useIDBKeyval

Category
Export Size
828 B
Package
@reause/integrations
Last Changed
5 days ago

Wrapper for idb-keyval.

Demo

Install idb-keyval as a peer dependency

bash
npm i idb-keyval@^6

Usage

tsx
import { 
useIDBKeyval
} from '@reause/integrations'
// bind object const [
storedObject
,
setStoredObject
, {
isFinished
}] =
useIDBKeyval
('my-idb-keyval-store', {
hello
: 'hi',
greeting
: 'Hello',
}) // update object — explicit write (no deep watcher)
setStoredObject
({ ...
storedObject
,
hello
: 'hola' })
// bind boolean const [
flag
] =
useIDBKeyval
('my-flag', true)
// bind number const [
count
,
setCount
] =
useIDBKeyval
('my-count', 0)
// awaiting the IDB transaction await
setCount
(10)
console
.
log
('IDB transaction finished!')
// delete data from the idb store await
setStoredObject
(null)

Cross-tab syncing

Changes are automatically synced across browser tabs using the BroadcastChannel API. This is enabled by default and can be disabled via the listenToStorageChanges option.

tsx
// disable cross-tab syncing
const [
data
] =
useIDBKeyval
('my-key', 'default', {
listenToStorageChanges
: false })

Type Declarations

ts
export interface UseIDBKeyvalSerializer<T> {
    read: (raw: unknown) => T;
    write: (value: T) => unknown;
}

export interface UseIDBOptions<T> {
    window?: Window;
    onError?: (error: unknown) => void;
    writeDefaults?: boolean;
    serializer?: UseIDBKeyvalSerializer<T>;
    listenToStorageChanges?: boolean;
    deep?: boolean;
    shallow?: boolean;
    flush?: 'pre' | 'post' | 'sync' | 'async';
}

export interface UseIDBKeyvalControls {
    isFinished: boolean;
    isSupported: boolean;
}

export type UseIDBKeyvalReturn<T> = [
    data: T | null,
    setData: (value: T | null) => Promise<void>,
    controls: UseIDBKeyvalControls
]

export function useIDBKeyval<T>(key: IDBValidKey, initialValue: T, options?: UseIDBOptions<T>): UseIDBKeyvalReturn<T>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
adcf0 - fix(integrations): resolve useIDBKeyval audit findings (#803)
117ce - feat(integrations): add useIDBKeyval (#141)

Released under the MIT License. v0.1.8