fetch
?The fetch()
function is a built-in JavaScript function for making HTTP requests. Unlike Axios, fetch()
returns a Promise that resolves to the response of the request. It works well for interacting with REST APIs.
For this example, we'll use JSONPlaceholder, a free mock API that simulates real-world RESTful interactions. The API URL for fetching users is:
https://jsonplaceholder.typicode.com/users
First, let’s set up the React component that will handle CRUD operations.
If you haven’t already, create a React application:
npx create-react-app crud-api-react
cd crud-api-react
npm start
fetch
In the following examples, we'll use useState
and useEffect
to manage state and perform side effects, respectively. We will then use fetch
for the API calls.
import React, { useState, useEffect } from "react";
function CrudWithFetch() {
const [users, setUsers] = useState([]);
const [newUser, setNewUser] = useState({ name: "", email: "" });
const [editUser, setEditUser] = useState({ id: "", name: "", email: "" });
const apiUrl = "https://jsonplaceholder.typicode.com/users";
// Fetching data from API (Read)
useEffect(() => {
fetch(apiUrl)
.then((response) => response.json())
.then((data) => setUsers(data))
.catch((error) => console.error("Error fetching data:", error));
}, []);
// Creating a new user (Create)
const createUser = () => {
fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newUser),
})
.then((response) => response.json())
.then((data) => setUsers([...users, data]))
.catch((error) => console.error("Error creating user:", error));
};
// Updating a user (Update)
const updateUser = () => {
fetch(`${apiUrl}/${editUser.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(editUser),
})
.then((response) => response.json())
.then((data) => {
const updatedUsers = users.map((user) =>
user.id === data.id ? data : user
);
setUsers(updatedUsers);
})
.catch((error) => console.error("Error updating user:", error));
};
// Deleting a user (Delete)
const deleteUser = (id) => {
fetch(`${apiUrl}/${id}`, {
method: "DELETE",
})
.then(() => setUsers(users.filter((user) => user.id !== id)))
.catch((error) => console.error("Error deleting user:", error));
};
return (
<div>
<h1>CRUD with API in React using `fetch`</h1>
{/* Display users */}
<h2>Users List</h2>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} ({user.email})
<button onClick={() => deleteUser(user.id)}>Delete</button>
<button onClick={() => setEditUser(user)}>Edit</button>
</li>
))}
</ul>
{/* Create new user form */}
<h2>Create User</h2>
<input
type="text"
placeholder="Name"
value={newUser.name}
onChange={(e) => setNewUser({ ...newUser, name: e.target.value })}
/>
<input
type="email"
placeholder="Email"
value={newUser.email}
onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
/>
<button onClick={createUser}>Add User</button>
{/* Edit user form */}
{editUser.id && (
<div>
<h2>Edit User</h2>
<input
type="text"
value={editUser.name}
onChange={(e) => setEditUser({ ...editUser, name: e.target.value })}
/>
<input
type="email"
value={editUser.email}
onChange={(e) => setEditUser({ ...editUser, email: e.target.value })}
/>
<button onClick={updateUser}>Update User</button>
</div>
)}
</div>
);
}
export default CrudWithFetch;
createUser
sends a POST
request to the API to create a new user.newUser
state is passed as the body of the request, and the Content-Type
header is set to application/json
.createUser
sends a POST
request to the API to create a new user.newUser
state is passed as the body of the request, and the Content-Type
header is set to application/json
.useEffect
fetches the list of users when the component is mounted.GET
request is sent to the API, and the response is stored in the users
state.updateUser
sends a PUT
request to update the selected user’s data.editUser
state contains the updated information, which is sent as the body of the request.deleteUser
sends a DELETE
request to the API to remove a user.It's important to manage errors and loading states to improve the user experience:
.catch()
to handle any errors that may occur during the API requests.fetch()
is a native JavaScript method to make HTTP requests, unlike Axios, which is an external library.useState
to manage the state of the data in the component.useEffect
is used to fetch data when the component mounts.POST
for CreateGET
for ReadPUT
for UpdateDELETE
for DeletePerforming CRUD operations with an API in React using fetch
is simple and effective. By using React’s useState
and useEffect
hooks, combined with the native fetch
API, you can easily manage data in your React applications. This approach provides a lightweight solution for interacting with REST APIs, creating dynamic and responsive web applications.