*Welcome to this beginner-friendly guide on building a simple CRUD *(Create, Read, Update, Delete) application with React.js and IndexedDB, a web browser storage solution. In this tutorial, we'll walk through creating a basic application where users can input data, store it in the browser's IndexedDB, and manage that data using CRUD operations.
Prerequisites
Before we begin, make sure you have the following installed:
- Node.js and npm (Node Package Manager) β You can download and install them from nodejs.org.
- Basic understanding of JavaScript and React concepts.
Setting Up the Project
First, let's set up our React project using Create React App.
npx create-react-app indexeddb-crud-app
cd indexeddb-crud-app
npm install dexie --save
In this guide, we'll use Dexie.js, a wrapper library that simplifies working with IndexedDB.
Creating the CRUD Application
*1. Creating the Database *
Inside your src folder, create a db.js file. This file will define your IndexedDB database schema and its operations.
import Dexie from 'dexie';
const db = new Dexie('MyDatabase');
db.version(1).stores({
data: '++id, name, message',
});
export default db;
In this code, we define a data store with id, name, and message fields.
2. Building the CRUD Operations
Next, let's create a DataManager.js file inside your src folder. This file will handle all CRUD operations using Dexie.js.
import db from './db';
export const insertData = async (name, message) => {
try {
await db.data.add({ name, message });
console.log('Data inserted successfully.');
} catch (error) {
console.error('Error inserting data:', error);
}
};
export const getAllData = async () => {
try {
const data = await db.data.toArray();
return data;
} catch (error) {
console.error('Error getting data:', error);
return [];
}
};
export const updateData = async (id, name, message) => {
try {
await db.data.update(id, { name, message });
console.log('Data updated successfully.');
} catch (error) {
console.error('Error updating data:', error);
}
};
export const deleteData = async (id) => {
try {
await db.data.delete(id);
console.log('Data deleted successfully.');
} catch (error) {
console.error('Error deleting data:', error);
}
};
In this file, we define functions for inserting, retrieving, updating, and deleting data.
3. Building the React Components
Now, let's create React components to handle user interactions.
FormComponent.js
import React, { useState } from 'react';
import { insertData } from './DataManager';
const FormComponent = () => {
const [name, setName] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
insertData(name, message);
setName('');
setMessage('');
};
return (
<form onSubmit={handleSubmit}>
<input
type='text'
placeholder='Enter name'
value={name}
onChange={(e) => setName(e.target.value)}
/>
<textarea
placeholder='Enter message'
value={message}
onChange={(e) => setMessage(e.target.value)}
></textarea>
<button type='submit'>Submit</button>
</form>
);
};
export default FormComponent;
DataListComponent.js
import React, { useState, useEffect } from 'react';
import { getAllData, deleteData } from './DataManager';
const DataListComponent = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await getAllData();
setData(result);
};
fetchData();
}, []);
const handleDelete = async (id) => {
await deleteData(id);
const updatedData = await getAllData();
setData(updatedData);
};
return (
<ul>
{data.map((item) => (
<li key={item.id}>
{item.name}: {item.message}
<button onClick={() => handleDelete(item.id)}>Delete</button>
</li>
))}
</ul>
);
};
export default DataListComponent;
App.js
import React from 'react';
import FormComponent from './FormComponent';
import DataListComponent from './DataListComponent';
const App = () => {
return (
<div>
<h1>IndexedDB CRUD Application</h1>
<FormComponent />
<DataListComponent />
</div>
);
};
export default App;
4. Testing the Application
Run your application using npm start and test the CRUD operations. You can now add, view, update, and delete data in your application.
Conclusion
Congratulations! You've successfully built a simple CRUD application with React.js and IndexedDB. This beginner-friendly guide has covered the basics of setting up a React application, creating an IndexedDB database, and performing CRUD operations.
Feel free to enhance your application by adding more features or styling. Happy coding!
Top comments (0)