indexedDB 사용하기 with react-indexed-db

백우진·2023년 1월 10일
3
post-thumbnail

indexedDB란?

IndexedDB는 파일이나 블롭 등 많은 양의 구조화된 데이터를 클라이언트에 저장하기 위한 로우 레벨 API


장점

  1. 많은 양의 구조화된 데이터를 클라이언트에 저장할 수 있다.
  2. Javascript 기반의 객체지향 데이터베이스이다.
  3. 트랜잭션을 사용하며 Key-Value 데이터베이스이다.
  4. 비동기식 API 이다.

react-indexed-db 라이브러리

react-indexed-db
react-indexed-db is a service that wraps IndexedDB database in an "easier to use" service. It exposes very simple promises API to enable the usage of IndexedDB without most of it plumbing.

라이브러리를 사용하면 indexedDB를 쉽게 핸들링 할 수 있어 사용하기로 함.


설치

npm install react-indexed-db

초기 세팅

//DBConfig.js|tsx
 
export const DBConfig = {
  name: 'MyDB',
  version: 1,
  objectStoresMeta: [
    {
      store: 'people',
      storeConfig: { keyPath: 'id', autoIncrement: true },
      storeSchema: [
        { name: 'name', keypath: 'name', options: { unique: false } },
        { name: 'email', keypath: 'email', options: { unique: false } }
      ]
    }
  ]
};
//App.js|tsx
 
import React from 'react';
import { DBConfig } from './DBConfig';
import { initDB } from 'react-indexed-db';
 
initDB(DBConfig);
 
const App: React.FC = () => {
  return <div>...</div>;
};

getAll() 사용하기

It returns an array of all the items in the given objectStore. getAll returns a promise that is resolved when we have the array of items or rejected if an error occurred.

objectStore에 있는 모든 항목의 배열을 반환한다.

// Hooks
import { useIndexedDB } from 'react-indexed-db';
 
function ShowAll() {
  const { getAll } = useIndexedDB('people');
  const [persons, setPersons] = useState();
 
  useEffect(() => {
    getAll().then(personsFromDB => {
      setPersons(personsFromDB);
    });
  }, []);
 
  return (
    <div>
      {personsFromDB.map(person => (
        <span>{person}</span>
      ))}
    </div>
  );
}

add(value, key) 사용하기

It Adds to the given objectStore the key and value pair. The firt parameter is the value and the second is the key (if not auto-generated). add returns a promise that is resolved when the value was added or rejected if an error occurred.

정해진 ObjectStore에 Key,Value 쌍을 추가한다.

// Hooks
import { useIndexedDB } from 'react-indexed-db';
 
function AddMore() {
  const { add } = useIndexedDB('people');
  const [person, setPerson] = useState();
 
  const handleClick = () => {
    add({ name: 'name', email: 'email' }).then(
      event => {
        console.log('ID Generated: ', event.target.result);
      },
      error => {
        console.log(error);
      }
    );
  };

delete(key) 사용하기

deletes the object that correspond with the key from the objectStore. The first parameter is the key to delete. delete returns a promise that is resolved when the value was deleted or rejected if an error occurred.

ObjectStore에서 키에 해당하는 객체를 삭제한다.


// Hooks
import { useIndexedDB } from 'react-indexed-db';
 
function Delete() {
  const { deleteRecord } = useIndexedDB('people');
 
  const handleClick = () => {
    deleteRecord(3).then(event => {
      alert('Deleted!');
    });
  };

참고자료

  1. https://www.npmjs.com/package/react-indexed-db
profile
안녕하세요.

0개의 댓글