CRUD Operations in React JS
CRUD operations in React refer to the basic operations you can perform on data: Create, Read, Update, and Delete. These operations allow you to manage data in your application by interacting with a server or local state. Here’s a breakdown of how you can implement each CRUD operation in React:
1. Create
Creating new data involves sending a POST request to the server with the data you want to create. This is typically done through a form where users input the data they want to add.
Example using fetch
API
import React, { useState } from 'react';
function CreateData() {
const [inputValue, setInputValue] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleSubmit = async (event) => {
event.preventDefault();
setLoading(true);
try {
const response = await fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ value: inputValue }),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
console.log(result); // Handle the result as needed
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button type="submit" disabled={loading}>
{loading ? 'Creating...' : 'Create'}
</button>
{error && <p>Error: {error.message}</p>}
</form>
);
}
export default CreateData;
2. Read
Reading data involves sending a GET request to retrieve data from the server. You typically fetch data when the component mounts and display it in the UI.
Example using fetch
API
import React, { useState, useEffect } from 'react';
function ReadData() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
setData(result);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default ReadData;
3. Update
Updating data involves sending a PUT or PATCH request to modify existing data on the server. This typically involves a form where users can edit data.
Example using fetch
API
import React, { useState } from 'react';
function UpdateData() {
const [inputValue, setInputValue] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleUpdate = async () => {
setLoading(true);
try {
const response = await fetch('https://api.example.com/data/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ value: inputValue }),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
console.log(result); // Handle the result as needed
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button onClick={handleUpdate} disabled={loading}>
{loading ? 'Updating...' : 'Update'}
</button>
{error && <p>Error: {error.message}</p>}
</div>
);
}
export default UpdateData;
4. Delete
Deleting data involves sending a DELETE request to remove a resource from the server. This operation is often triggered by a user action like clicking a delete button.
Example using fetch
API
import React, { useState } from 'react';
function DeleteData() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleDelete = async () => {
setLoading(true);
try {
const response = await fetch('https://api.example.com/data/1', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
console.log(result); // Handle the result as needed
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
return (
<div>
<button onClick={handleDelete} disabled={loading}>
{loading ? 'Deleting...' : 'Delete'}
</button>
{error && <p>Error: {error.message}</p>}
</div>
);
}
export default DeleteData;
Key Points for CRUD Operations
State Management:
- Use React’s
useState
to manage input values, loading states, and error handling.
- Use React’s
Effect Hook:
- Use
useEffect
for fetching data when the component mounts (for Read operations).
- Use
Handling Requests:
- Use
fetch
oraxios
to make HTTP requests. - Set appropriate HTTP methods (
POST
,GET
,PUT
,PATCH
,DELETE
) based on the operation.
- Use
Error Handling:
- Always handle errors to manage issues such as network problems or server errors.
User Feedback:
- Provide feedback to users during loading and error states to enhance user experience.
Summary
CRUD operations in React involve creating, reading, updating, and deleting data by interacting with a server. You can use JavaScript’s fetch
API or axios
for making HTTP requests to perform these operations. Proper management of state and error handling ensures that the application behaves correctly and provides a good user experience.