local-db-storage
December 4, 2024 · View on GitHub
IndexedDBwrapper that mimicslocalStorageAPI
Install
npm install local-db-storage
Why
- Simple.
localStoragelike API, without the complications ofIndexedDB. - Capacity.
IndexedDBcan store hundred of megabytes to gigabytes of data.localStoragelimit is around 5-10MB. - Performance.
IndexedDBis async and doesn't block the UI.IndexedDBcan store objects without serialization which shaves off the time to doJSON.parse()andJSON.stringify()that's needed when working withlocalStorage. - No good alternatives. The most popular library
localForage(25k stars) is complex and unmaintained. - Availability.
IndexedDBis available both in Web Worker and Service Worker,localStorageis not. You can write data in those places and then access it in the main thread. - Maintenance. I've been consistently maintaining many open-source libraries including
use-local-storage-statewith ~500k downloaders per month.
Usage
import dbStorage from 'local-db-storage'
async function addTodo(todo): Promise<void> {
await dbStorage.setItem(todo.id, todo)
}
async function getTodo(id: string): Promise<Todo> {
await dbStorage.getItem<Todo>(id)
}
API
getItem<T>(key: string): Promise<T>
Like localStorage.getItem() but async.
setItem(key: string, value: any): Promise<void>
Like localStorage.setItem() but async.
Note: It supports non-primitive values (ex: objects). It also supports circular references.
removeItem(key: string): Promise<void>
Like localStorage.removeItem() but async.
clear(): Promise<void>
Like localStorage.clear() but async.
DBStorage(name: string)
Creates a new DBStorage instance.
import { DBStorage } from 'local-db-storage'
const dbStorage = new DBStorage('my-custom-db-storage')
await dbStorage.setItem('initial', 'hello world')
Related
use-db— React hook forIndexedDBthat uses this library and mimicssetStateAPI.use-local-storage-state— React hook that persists data inlocalStorage.use-session-storage-state— React hook that persists data insessionStorage.