An open API service indexing awesome lists of open source software.

https://github.com/hc-oss/use-indexeddb

Lightweight (1KB gzipped) hook w/ promises for easy IndexedDB access in React ⚓
https://github.com/hc-oss/use-indexeddb

hacktoberfest hooks indexeddb lightweight react react-hooks server-side-rendering ssr-safe typescript

Last synced: 7 months ago
JSON representation

Lightweight (1KB gzipped) hook w/ promises for easy IndexedDB access in React ⚓

Awesome Lists containing this project

README

        

# use-indexeddb

Lightweight (1KB gzipped) hooks w/ promises for easy IndexedDB access in React ⚓

[![Storybook](https://cdn.jsdelivr.net/gh/storybookjs/brand@master/badge/badge-storybook.svg)](https://use-indexeddb.pages.dev)
[![GitHub Actions Status](https://github.com/harshzalavadiya/use-indexeddb/workflows/CI/badge.svg)](https://github.com/harshzalavadiya/use-indexeddb/actions)
[![NPM](https://img.shields.io/npm/v/use-indexeddb.svg)](https://npm.im/use-indexeddb)
[![gzip](https://badgen.net/bundlephobia/minzip/use-indexeddb@latest)](https://bundlephobia.com/result?p=use-indexeddb@latest)

## 🔧 Installation

```bash
npm i use-indexeddb # npm
yarn add use-indexeddb # yarn
```

## 📚 Storybook

[see demo on storybook](https://use-indexeddb.pages.dev/)

## ✨ Features

- 🍃 Lightweight (~3KB gzipped) [no dependencies]
- 🧠 Automatic modal type inference like `useIndexedDBStore()`
- ✅ SSR Safe
- 🤞 Simple [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) based api

## 📦 Examples

1. [add](#addvalue-key)
2. [getByID](#getbyidid)
3. [getAll](#getall)
4. [getOneByKey](#getonebykeykeypath-value)
5. [getManyByKey](#getmanybykeykeypath-value)
6. [update](#updatevalue-key)
7. [deleteByID](#deletebyidid)
8. [deleteAll](#deleteall)
9. [openCursor](#opencursorcursorcallback-keyrange)

### Full Example

```tsx
import React from "react";
import setupIndexedDB, { useIndexedDBStore } from "use-indexeddb";

// Database Configuration
const idbConfig = {
databaseName: "fruity-db",
version: 1,
stores: [
{
name: "fruits",
id: { keyPath: "id", autoIncrement: true },
indices: [
{ name: "name", keyPath: "name", options: { unique: false } },
{ name: "quantity", keyPath: "quantity" },
],
},
],
};

const Example = () => {
useEffect(() => {
setupIndexedDB(idbConfig)
.then(() => console.log("success"))
.catch(e => console.error("error / unsupported", e));
}, []);

const { add } = useIndexedDBStore("fruits");

const insertFruit = () => {
add({ name: "Mango 🥭", quantity: 2 }).then(console.log);
};

return Insert;
};

export default Example;
```

### `add(value, key?)`

Inserts given `value` record to selected store, second param is optional key useful if auto-increment is disabled

By default commit is enabled after each transaction so changes are reflected in indexedDB instantly

```jsx
import { useIndexedDBStore } from "use-indexeddb";

function Example() {
const { add } = useIndexedDBStore("fruits");

const onClick = () => {
add({ name: "Mango 🥭", quantity: 2 })
.then(d => console.log(`Added Fruit with ID ${d}`))
.catch(console.error);
};

return Add;
}
```

### `getByID(id)`

Retrive record by ID

```jsx
import { useIndexedDBStore } from "use-indexeddb";

function Example() {
const { getByID } = useIndexedDBStore("fruits");

const onClick = () => {
getByID(1)
.then(console.log)
.catch(console.error);
};

return Get - ID 1;
}
```

### `getAll()`

Retrive all records from provided store

```jsx
import { useIndexedDBStore } from "use-indexeddb";

function Example() {
const { getAll } = useIndexedDBStore("fruits");

const onClick = () => {
getAll()
.then(console.log)
.catch(console.error);
};

return Get All Fruits;
}
```

### `getOneByKey(keyPath, value)`

Retrives single record if any row matches with given `keyPath` having `value`

```jsx
import { useIndexedDBStore } from "use-indexeddb";

function Example() {
const { getOneByKey } = useIndexedDBStore("fruits");

const onClick = () => {
getOneByKey("quantity", 2)
.then(console.log)
.catch(console.error);
};

return Get Fruit w/ Qty 2;
}
```

### `getManyByKey(keyPath, value)`

Retrives multiple records in form of array if row matches with given `keyPath` having `value`

```jsx
import { useIndexedDBStore } from "use-indexeddb";

function Example() {
const { getManyByKey } = useIndexedDBStore("fruits");

const onClick = () => {
getManyByKey("quantity", 2)
.then(console.log)
.catch(console.error);
};

return Get All Fruits w/ Qty 2;
}
```

### `update(value, key?)`

Inserts or Updates given `value` in store by `ID`

```jsx
import { useIndexedDBStore } from "use-indexeddb";

function Example() {
const { update } = useIndexedDBStore("fruits");

const onClick = () => {
update({ id: 1, name: "Strawberry 🍓", quantity: 20 })
.then(console.log)
.catch(console.error);
};

return Update Fruid #1 to Strawberry;
}
```

### `deleteByID(id)`

Deletes record by ID

```jsx
import { useIndexedDBStore } from "use-indexeddb";

function Example() {
const { deleteByID } = useIndexedDBStore("fruits");

const onClick = () => {
deleteByID(1)
.then(console.log)
.catch(console.error);
};

return Delete Fruit with ID 1;
}
```

### `deleteAll()`

Deletes all records

```jsx
import { useIndexedDBStore } from "use-indexeddb";

function Example() {
const { deleteAll } = useIndexedDBStore("fruits");

const onClick = () => {
deleteAll()
.then(console.log)
.catch(console.error);
};

return Delete All Fruits;
}
```

### `openCursor(cursorCallback, keyRange?)`

You can use `openCursor` to iterate over objects one by one within given `keyRange`

```jsx
import { useIndexedDBStore } from "use-indexeddb";

function Example() {
const { openCursor } = useIndexedDBStore("fruits");

const onClick = () => {
openCursor(e => {
const c = e.target.result;
if (c) {
console.log(c);
c.continue();
} else {
console.log("that's all folks");
}
});
};

return Open Cursor;
}
```

## 🤠 Credits

- This library takes inspiration from [react-indexed-db](https://github.com/assuncaocharles/react-indexed-db)
- [TypeScript](https://github.com/microsoft/typescript)
- [TSDX](https://github.com/jaredpalmer/tsdx)

## 📜 License

MIT © [harshzalavadiya](https://github.com/harshzalavadiya)