How to use indexDb in react
Download dependencies
npm install localforage
Next use it like using localstore
import React, { useEffect } from 'react'; import localForage from 'localforage'; const App = () => { useEffect(() => { // Save data async function storeData() { try { await ('user', { id: 1, name: 'John Doe' }); // Read data const userData = await ('user'); (userData); } catch (err) { // Error handling (err); } } storeData(); }, []); return ( <div> <h1>Welcome to IndexedDB with localForage</h1> </div> ); }; export default App;
Extension: Front-end offline storage capability: How to cleverly use IndexedDB in React
Front-end offline storage capability: How to cleverly use IndexedDB in React
Preface
When we develop complex web applications, we often need to store a large amount of data on the client side. You may have heard of itlocalStorage
orsessionStorage
, but they have limited storage space and functionality. What we are going to talk about today is a more powerful technology:IndexedDB。
What is IndexedDB
IndexedDB is a non-relational database running in the browser. It allows you to store large amounts of data and has high performance query capabilities. Unlike localStorage that can only store strings, IndexedDB can store various types of data, such as files, blobs, and other types you can think of.
The capability of IndexedDB
-
Store large amounts of data: It can store
localStorage
More data, and no fixed size limit, are often based on a certain percentage of the user's disk size. - Complex data storage: Ability to store more complex data types.
- Excellent query performance: IndexedDB supports indexes, you can create indexes and quickly retrieve data without traversing the entire database.
- Offline apps: When the user does not have a network, the application can still access the previously stored data.
- Transaction support: IndexedDB supports transactions, you can perform complex data operations and also have the ability to roll back.
- asynchronous: All operations are asynchronous, which also means that it will not block your UI threads and the user experience is better.
Using IndexedDB in React Projects
OK, now we know that IndexedDB is a good thing, so how do you use it in React?
This article will introduce two ways to use IndexedDB.
1. Native method
Let's create a simple React hook to show how to use the native IndexedDB API.
import { useEffect, useState } from 'react'; const useIndexedDB = (dbName, storeName) => { const [db, setDb] = useState(null); useEffect(() => { const request = (dbName, 1); = (event) => { ('Database error:', ); }; = (event) => { setDb(); }; = (event) => { const db = ; (storeName, { keyPath: 'id', autoIncrement: true }); }; }, [dbName, storeName]); const addData = (data) => { const transaction = ([storeName], 'readwrite'); const store = (storeName); (data); }; return [db, addData]; };
This Hook is very basic, it opens the database and allows you to add data to the database.
2. Use localForage
Now let's see how to use itlocalForage
- A quick and easy local repository to use IndexedDB in a more concise way. First, you need to install itlocalForage
:
npm install localforage
Now you can use it to simplify the operation of IndexedDB:
import localForage from 'localforage'; ('somekey', 'somevalue') .then(() => { return ('somekey'); }) .then((value) => { // Here is our data (value); }) .catch((err) => { // Something went wrong! (err); });
()
and()
All return Promise, which makes them convenient to use with async/await.
import React, { useEffect } from 'react'; import localForage from 'localforage'; const App = () => { useEffect(() => { // Save data async function storeData() { try { await ('user', { id: 1, name: 'John Doe' }); // Read data const userData = await ('user'); (userData); // => {id: 1, name: "John Doe"} } catch (err) { // Error handling (err); } } storeData(); }, []); return ( <div> <h1>Welcome to IndexedDB with localForage</h1> </div> ); }; export default App;
In this example, we create a name calledApp
React component, in componentuseEffect
In Hook, we wrote astoreData
ofasync
Functions to interact asynchronously with IndexedDB. Let's use it firstsetItem
Methods store data into IndexedDB and usegetItem
Read the data and print them out.
localForage
Support callbacks andPromise
API in form, which makes it very easy to use in modern JavaScript or TypeScript applications. It will also automatically back to using WebSQL or localStorage based on browser support, which provides better compatibility for your application.
Actual combat
Next let's try to build a small to-do application that will use React and IndexedDB native APIs to store data.
Step 1: Create an IndexedDB database and object storage
Create the portal file for the React applicationAnd write the following:
import React, { useState, useEffect } from 'react'; function App() { const [db, setDb] = useState(null); const [todos, setTodos] = useState([]); const [task, setTask] = useState(''); useEffect(() => { let request = ('todoDB', 1); = (e) => { ('Error opening db', e); }; = (e) => { setDb(); }; = (e) => { let db = ; let store = ('todos', { keyPath: 'id', autoIncrement: true }); ('task', 'task', { unique: false }); }; }, []); // ...The subsequent content will be added here... return ( <div> <h1>Todo App with IndexedDB</h1> {/* To-do form and list display will be added here */} </div> ); } export default App;
Step 2: Implement the function of adding and displaying to-do items
Now, we implement the functionality within the component to add new todos to IndexedDB and read the todo list from the database.
renew, add the following:
// ...Previous code...function addTodo() { const transaction = (['todos'], 'readwrite'); const store = ('todos'); let request = ({ task }); = () => { ('Task added'); setTask(''); // Clear input loadTodos(); // Reload the to-do list }; } function loadTodos() { let transaction = (['todos'], 'readonly'); let store = ('todos'); let request = (); let todos = []; = (e) => { let cursor = ; if (cursor) { (); (); } else { setTodos(todos); } }; } // Make sure the data is loadeduseEffect(() => { if (db) { loadTodos(); } }, [db]); // ...Previous code...return ( <div> {/* Other codes */} <input type="text" value={task} onChange={(e) => setTask()} /> <button onClick={addTodo}>Add Task</button> <ul> {((todo) => ( <li key={}>{}</li> ))} </ul> </div> ); // ...Previous code...
The above code completes the following functions:
- pass
useEffect
Hook creates or opens a namedtodoDB
If the IndexedDB database does not exist, it will create a name calledtodos
object storage. - use
addTodo
Function to add new tasks to the database. - use
loadTodos
The function querys all to-do items in IndexedDB and sets them into the component state so that these to-do items can be displayed in the React component. - A simple form is provided to enter new to-do items and add them to the list.
At this point, we already have a basic to-do application that can store data using IndexedDB. Of course, many enhancements are needed in actual applications, such as error handling, user input verification, and deletion and editing functions of to-do items. But this example is enough to illustrate how to use IndexedDB directly in React, and to develop web applications that can persist in storing user data.
in conclusion
IndexedDB is indeed a powerful tool, especially suitable for web applications that need to store and operate large amounts of and/or complex data. However, remember that its API is not as simple and straightforward as localStorage, so in most cases, uselocalForage
Waiting for libraries can greatly simplify this process.
This is all about this article about how to use indexDb in react. For more related content about using indexDb in react, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!