IndexedDB는 파일이나 블롭 등 많은 양의 구조화된 데이터를 클라이언트에 저장하기 위한 로우 레벨 API
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>;
};
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>
);
}
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);
}
);
};
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!');
});
};