0.0.1 • Published 5 years ago

@hako1912/use-indexeddb v0.0.1

Weekly downloads
-
License
-
Repository
-
Last release
5 years ago

react-use-indexeddb

Redux のように IndexedDB を使うための React Hooks。
Dexieを使用します。

Install

yarn add @hako1912/use-indexeddb

Usage

エンティティ型を定義します。

// Person.ts
import { Entity } from "@hako1912/react-use-indexeddb";

export type Person = {
  name: string;
  age: number;
} & Entity;

Dexieの Database オブジェクトを作ります。

// Database.ts
import Dexie from "dexie";
import { Person } from "./Person";

class Database extends Dexie {
  persons: Dexie.Table<Person, string>;

  constructor() {
    super("Database");

    this.version(1).stores({
      persons: "&id, name, age"
    });

    this.persons = this.table("persons");
  }
}

export const db = new Database();

詳細:
https://dexie.org/docs/Typescript

React コンポーネントの中でuseIndexedDbを呼びます。
useIndexedDbはデータのリストとデータの操作関数を返します。

import { useIndexedDb } from "@hako1912/react-use-indexeddb";

const myComponent = () => {
  const [persons, insertPerson, updatePerson, deletePerson] = useIndexedDb(
    db,
    db.persons
  );

  return (
    <>
      {persons.map(person => (
        <p key={person.id}>{person.name}</p>
      ))}
    </>
  );
};