이전 기사에서 우리는 IndexedDB의 래퍼 인 Dexie에 대해 논의했습니다. 이 기사에서는 INDEXEDDB에 대해 논의합니다. 브라우저에 정보를 저장하는 데 일반적으로 사용되는이 LocalStorage API에 익숙해야합니다. 마찬가지로, IndexedDB는 클라이언트 측 스토리지에 사용됩니다.
mdn 문서 설명 :
indexeddb는 파일/블로브를 포함하여 상당한 양의 구조화 된 데이터를 클라이언트 측 스토리지하기위한 저수준 API입니다. 이 API는 인덱스를 사용 하여이 데이터의 고성능 검색을 가능하게합니다. 웹 스토리지는 소수의 데이터를 저장하는 데 유용하지만 더 많은 양의 구조화 된 데이터를 저장하는 데 유용하지 않습니다.
indexeddb는 솔루션을 제공합니다. 이것은 MDN의 IndexEdDB 커버리지의 메인 방문 페이지입니다. 여기에서는 전체 API 참조 및 사용 가이드, 브라우저 지원 세부 사항 및 주요 개념에 대한 설명에 대한 링크를 제공합니다.
mdn은 예제 Github 리포지토리를 제공하며 script/todo.js.
스크립트는 Window.onload
를 사용하여 초기화됩니다.
window.onload = () => { }
// Let us open our database const DBOpenRequest = window.indexedDB.open('toDoList', 4);
// Register two event handlers to act on the database being opened successfully, or not DBOpenRequest.onerror = (event) => { note.appendChild(createListItem('Error loading database.')); };
DBOpenRequest.onsuccess = (event) => { note.appendChild(createListItem('Database initialised.')); // Store the result of opening the database in the db variable. This is used a lot below db = DBOpenRequest.result; // Run the displayData() function to populate the task list with all the to-do list data already in the IndexedDB displayData(); };
// Open a read/write DB transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); // Call an object store that's already been added to the database const objectStore = transaction.objectStore('toDoList'); // Make a request to add our newItem object to the object store const objectStoreRequest = objectStore.add(newItem[0]); objectStoreRequest.onsuccess = (event) => { // process data on success. } // Report on the success of the transaction completing, when everything is done transaction.oncomplete = () => { note.appendChild(createListItem('Transaction completed: database modification finished.')); // Update the display of data to show the newly added item, by running displayData() again. displayData(); }; // Handler for any unexpected error transaction.onerror = () => { note.appendChild(createListItem(`Transaction not opened due to error: ${transaction.error}`)); };, 'readwrite'); // 이미 데이터베이스에 추가 된 객체 저장소에 전화 const ObjectStore = transaction.objectStore ( 'Todolist'); // 객체 저장소에 새로운 객체를 추가하도록 요청합니다. const objectStoreRequest = ObjectStore.add (newitem [0]); ObjectStoreRequest.onsuccess = (이벤트) => { // 성공에 대한 데이터를 처리합니다. } // 모든 작업이 완료되면 거래 완료의 성공에 대한보고 transaction.oncomplete = () => { 참고. AppendChild (CreateListItem ( '트랜잭션 완료 : 데이터베이스 수정 완료'); // displayData ()를 다시 실행하여 새로 추가 된 항목을 표시하려면 데이터 표시를 업데이트합니다. displayData (); }; // 예기치 않은 오류에 대한 핸들러 transaction.onerror = () => { 참고. AppendChild (CreateListItem (`오류로 인해 트랜잭션이 열리지 않음 : $ {transaction.error}`); };
지금까지 레코드를 추가하는 데 필요한 코드가 많이 있다는 것을 알게 될 것입니다. OnError 및 OnSuccess와 같은 비동기 콜백이 있습니다. 이것은이 스택 교환 답변에 지적됩니다.
이 indexeddb 처리를 단순화하려면 Dexie를 사용할 수 있습니다.
export function AddFriendForm({ defaultAge } = { defaultAge: 21 }) { const [name, setName] = useState(''); const [age, setAge] = useState(defaultAge); const [status, setStatus] = useState(''); async function addFriend() { try { // Add the new friend! const id = await db.friends.add({ name, age }); setStatus(`Friend ${name} successfully added. Got id ${id}`); setName(''); setAge(defaultAge); } catch (error) { setStatus(`Failed to add ${name}: ${error}`); } } return (내보내기 함수 addfriendform ({defaultage} = {기본값 : 21}) { const [name, setName] = usestate ( ''); const [age, setage] = usestate (기본값); const [status, setstatus] = usestate ( ''); Async 함수 addfriend () { 노력하다 { // 새 친구 추가! const id = db.friends.add ({{ 이름, 나이 }); setStatus (`friend $ {name}가 성공적으로 추가되었습니다. id $ {id}`); setName ( ''); 설정 (기본값); } catch (오류) { setStatus (``$ {name}을 추가하지 못했습니다 : $ {error}`); } } 반품 ({status}
Name: setName(ev.target.value)} /> Age: setAge(Number(ev.target.value))} /> > ); }
{상태}
이름: setName (ev.target.value)} /> 나이: 설정 (NUMBER (EV.TARGET.VALUE))} /> 추가 > ); }이 래퍼 API는 Prisma 및 Drizzle과 같은 Orms를 상기시켜줍니다.
ThinkThroo에서 우리는 큰 오픈 소스 프로젝트를 연구하고 건축 가이드를 제공합니다. 우리는 프로젝트에서 사용할 수 있도록 Tailwind로 제작 된 Resubale 구성 요소를 개발했습니다. 우리는 Next.js, React 및 Node Development Services를 제공합니다.
프로젝트를 논의하기 위해 우리와 회의를 예약하십시오.
https://www.reddit.com/r/sveltejs/comments/15rj12h/any_downsides_to_using_indexeddb_vs_localstorage/
https://softwareengineering.stackexchange.com/questions/219953/how-is-localstorage-different-from-indexeddb
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3