Using the Fetch API in React
The Fetch API is a built-in JavaScript feature used to send HTTP requests and retrieve data from external servers. In React applications, it is commonly used to fetch users, products, posts, weather information, and other dynamic data from APIs. It returns a Promise that can be handled using .then() and .catch() or async/await.
Course: JustAcademy React JS Training
Course Demo: Register for React JS Course Demo
1. What Is the Fetch API?
The Fetch API provides a modern way to make network requests from JavaScript. It allows a React application to communicate with a backend server and retrieve or send information.
For example, when a user opens an online shopping website, the application can use Fetch to request product details from an API and display them on the screen.
Common Uses of the Fetch API
- Fetching user information from a server.
- Displaying products and prices in an e-commerce application.
- Retrieving news articles and blog posts.
- Loading weather information from a weather API.
- Submitting forms to a backend server.
- Sending login or registration details to an API.
- Updating and deleting records through supported API endpoints.
2. How Does the Fetch API Work?
The Fetch API follows an asynchronous request-and-response process. It sends a request to a specified URL and provides a Response object when the server responds.
React Component
|
v
Call fetch(URL)
|
v
Send HTTP Request
|
v
Server Processes Request
|
v
Receive Response Object
|
v
Check Response Status
|
v
Parse Response Body
|
v
Update React State
|
v
Display Data in UI
Steps Explained
- Request: Call
fetch() with the API URL.
- Response: Receive a Response object from the server.
- Status check: Check whether the HTTP response indicates success.
- Parsing: Convert the response body into JSON or another suitable format.
- State update: Store the retrieved data in React state.
- Rendering: React renders the updated information in the component.
3. Basic Syntax of Fetch
The basic syntax accepts a URL and an optional configuration object.
fetch(url, options)
.then(response => {
// Handle the response
})
.catch(error => {
// Handle network or other errors
});
The options argument can specify the HTTP method, headers, request body, credentials, and other request settings.
Example
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => {
if (!response.ok) {
throw new Error("Request failed");
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error.message);
});
Explanation
fetch() starts the request.
response.ok is true when the HTTP status is in the 200–299 range.
response.json() reads and parses the response body as JSON.
.then() processes the successful result.
.catch() handles rejected Promises and errors thrown in the Promise chain.
Important: Fetch does not automatically reject a Promise for HTTP errors such as 404 or 500. Always check response.ok when an unsuccessful HTTP status should be treated as an error.
4. What Is a Promise?
A Promise is a JavaScript object representing the eventual result of an asynchronous operation. Fetch uses Promises because network requests take time to complete.
A Promise can be in one of three states:
- Pending: The operation has not completed.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
Example Using a Promise
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => {
if (!response.ok) {
throw new Error("Post not found");
}
return response.json();
})
.then(post => {
console.log(post.title);
})
.catch(error => {
console.error(error.message);
});
Promise chaining allows one asynchronous step to pass its result to the next step.
5. Using async and await with Fetch
async and await provide a readable way to work with Promises. An async function returns a Promise, while await pauses that function until a Promise settles.
Example
async function fetchPost() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
if (!response.ok) {
throw new Error("Unable to fetch post");
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error.message);
}
}
fetchPost();
Advantages of async/await
- Makes asynchronous code easier to read.
- Allows request logic to be written in a sequential style.
- Works naturally with
try...catch error handling.
- Helps organize multiple dependent asynchronous operations.
6. Using Fetch in a React Component
In React, fetched information is usually stored in state. The useState Hook stores the data, while useEffect can initiate a request when a component is displayed or when its dependencies change.
Example: Fetch and Display Users
import { useEffect, useState } from "react";
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function getUsers() {
try {
setLoading(true);
setError("");
const response = await fetch(
"https://jsonplaceholder.typicode.com/users",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Failed to load users");
}
const data = await response.json();
setUsers(data);
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message || "Something went wrong");
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
getUsers();
return () => controller.abort();
}, []);
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
if (users.length === 0) {
return <p>No users found.</p>;
}
return (
<div>
<h2>User List</h2>
<ul>
{users.map(user => (
<li key={user.id}>
<strong>{user.name}</strong>
<p>Email: {user.email}</p>
<p>City: {user.address.city}</p>
</li>
))}
</ul>
</div>
);
}
export default UserList;
Code Explanation
useState([]) stores the user records returned by the API.
loading indicates whether the request is in progress.
error stores a readable error message.
useEffect() starts the request after the component commits.
async/await handles the asynchronous request.
AbortController allows the request to be cancelled during cleanup.
setUsers(data) updates state with the response data.
users.map() creates a list of user elements.
key={user.id} gives each rendered list item a stable key.
7. Understanding the Response Object
The Fetch API returns a Response object. It contains information about the server's response, including its status, headers, and body-reading methods.
| Property or Method |
Description |
response.ok |
Boolean indicating whether the HTTP status is between 200 and 299. |
response.status |
Numeric HTTP status code, such as 200 or 404. |
response.statusText |
Status text associated with the response, when provided. |
response.headers |
Provides access to response headers. |
response.json() |
Reads and parses the body as JSON. |
response.text() |
Reads the body as text. |
response.blob() |
Reads the body as a Blob, useful for binary data such as images. |
response.arrayBuffer() |
Reads the body as an ArrayBuffer. |
Note: Response body-reading methods are asynchronous. A response body is generally consumed once, so do not attempt to read the same body repeatedly without cloning the response first.
8. Making Different HTTP Requests
The Fetch API supports different HTTP methods. The method you choose depends on the operation supported by the backend API.
| Method |
Typical Purpose |
| GET |
Retrieve information. |
| POST |
Create a record or submit information. |
| PUT |
Replace an existing resource. |
| PATCH |
Partially update a resource. |
| DELETE |
Request deletion of a resource. |
8.1 GET Request
GET requests retrieve information from an API. GET is the default method when calling fetch() without specifying a method.
async function getPosts() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
if (!response.ok) {
throw new Error("Failed to retrieve posts");
}
return response.json();
}
8.2 POST Request
POST requests commonly submit data to create a resource. The backend determines whether the request is accepted and how the resource is processed.
async function createPost() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "Learning React",
body: "Practising the Fetch API",
userId: 1
})
}
);
if (!response.ok) {
throw new Error("Failed to create post");
}
return response.json();
}
Important POST Request Concepts
method specifies the HTTP method.
headers describes the content being sent.
Content-Type: application/json indicates that the request body contains JSON.
JSON.stringify() converts a JavaScript object into a JSON string.
- The response should be checked before parsing the body.
The JSONPlaceholder API is a demonstration service. Its write operations simulate changes and should not be treated as permanent database storage.
8.3 PUT Request
PUT is commonly used to replace a resource with the supplied representation.
async function replacePost() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1",
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
id: 1,
title: "Updated Title",
body: "Updated post content",
userId: 1
})
}
);
if (!response.ok) {
throw new Error("Failed to update post");
}
return response.json();
}
8.4 PATCH Request
PATCH is commonly used to update selected fields of a resource.
async function updatePostTitle() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1",
{
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "New Post Title"
})
}
);
if (!response.ok) {
throw new Error("Failed to update title");
}
return response.json();
}
8.5 DELETE Request
DELETE requests ask the server to remove a resource. Whether the resource is actually deleted depends on the API implementation.
async function deletePost() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1",
{
method: "DELETE"
}
);
if (!response.ok) {
throw new Error("Failed to delete post");
}
return true;
}
9. Sending Headers and Authentication Information
Headers provide additional information about an HTTP request. APIs may require content types, access tokens, or other headers.
Example with an Authorization Header
async function getPrivateData(token) {
const response = await fetch("https://api.example.com/profile", {
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json"
}
});
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
This is an illustrative example. Replace the endpoint with the actual API URL and follow its authentication requirements. Never place private API secrets directly in frontend source code, because browser-delivered code can be inspected by users.
10. Handling Loading, Error, and Empty States
A good React application should communicate what is happening while the request runs and when the server returns no data or an error.
| State |
Purpose |
Example Message |
| Loading |
Indicates that data is being retrieved. |
Loading data... |
| Success |
Displays the returned information. |
Data loaded successfully. |
| Error |
Communicates that the request failed. |
Unable to load data. |
| Empty |
Indicates that a successful response contains no records. |
No records found. |
Example of Conditional Rendering
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
if (data.length === 0) {
return <p>No data found.</p>;
}
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
In this example, data, loading, and error represent state values declared in the component. Make sure the data's initial value matches its expected type.
11. Fetching Data When a User Clicks a Button
Sometimes an application should fetch data only after a user performs an action. In this case, start the request from an event handler rather than automatically when the component mounts.
import { useState } from "react";
function LoadPost() {
const [post, setPost] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
async function handleLoadPost() {
try {
setLoading(true);
setError("");
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
if (!response.ok) {
throw new Error("Unable to load post");
}
const data = await response.json();
setPost(data);
} catch (err) {
setError(err.message || "Request failed");
} finally {
setLoading(false);
}
}
return (
<div>
<button onClick={handleLoadPost} disabled={loading}>
{loading ? "Loading..." : "Load Post"}
</button>
{error && <p>{error}</p>}
{post && (
<article>
<h2>{post.title}</h2>
<p>{post.body}</p>
</article>
)}
</div>
);
}
export default LoadPost;
This component sends a request when the button is clicked. The button is disabled during loading to reduce accidental repeated requests.
12. Cancelling Requests with AbortController
Sometimes a component no longer needs the result of a request. For example, a user may navigate away from a page or select a different record before the previous request completes. The AbortController API allows a Fetch request to be cancelled.
const controller = new AbortController();
fetch("https://jsonplaceholder.typicode.com/users", {
signal: controller.signal
})
.then(response => {
if (!response.ok) {
throw new Error("Request failed");
}
return response.json();
})
.then(data => console.log(data))
.catch(error => {
if (error.name === "AbortError") {
console.log("Request was cancelled");
} else {
console.error(error);
}
});
// Cancel the request when appropriate
controller.abort();
Why Request Cancellation Matters
- It can stop work that is no longer needed.
- It helps prevent obsolete requests from updating current UI state.
- It supports cleanup when a component's Effect is re-run or removed.
- It is especially useful for search suggestions and changing record IDs.
Aborting a request is not a substitute for handling every possible error. An application should distinguish cancellation from actual request failures.
13. Fetch API and CORS
CORS stands for Cross-Origin Resource Sharing. Browsers use this security mechanism to control whether a web page can read responses from a different origin.
For example, a React app running at http://localhost:5173 may request data from an API hosted on a different domain. The API server must allow the app's origin when the browser's CORS rules require it.
Common CORS Problems
- The API does not allow the frontend's origin.
- A required request header is not permitted.
- The server does not handle a preflight request correctly.
- Credentialed requests use incompatible CORS settings.
Solution: Configure CORS on the server or use an appropriately configured backend or development proxy. Adding mode: "no-cors" is generally not a solution for reading API JSON, because it produces an opaque response that JavaScript cannot inspect normally.
14. Common Fetch API Errors and Solutions
| Error or Problem |
Possible Cause |
Solution |
| 404 Not Found |
The requested resource does not exist. |
Verify the endpoint and resource ID. |
| 500 Internal Server Error |
The server encountered an error. |
Check server logs or contact the API owner. |
| Network error |
Connection failure, DNS issue, or blocked request. |
Check connectivity and the API URL. |
| CORS error |
The server does not permit the browser origin. |
Configure the server's CORS policy. |
| Unexpected JSON error |
The response body is not valid JSON. |
Check the response body and content type. |
| Data not displayed |
State or rendering logic is incorrect. |
Inspect state updates and browser console errors. |
| Repeated requests |
Effect dependencies or component lifecycle logic are incorrect. |
Review dependencies and cleanup behavior. |
| Stale data appears |
An older request finishes after a newer request. |
Abort obsolete requests or ignore outdated results. |
15. Fetch API vs Axios
Fetch and Axios are both commonly used to communicate with APIs. Fetch is built into modern browsers, while Axios is an external HTTP client library.
| Feature |
Fetch API |
Axios |
| Installation |
No extra package required in modern browsers. |
Requires installing the package. |
| JSON handling |
Call response.json(). |
JSON response data is usually available in response.data. |
| HTTP error statuses |
Check response.ok manually. |
Rejects the Promise by default for unsuccessful HTTP statuses. |
| Request configuration |
Uses the standard Fetch options. |
Provides additional configuration options. |
| Interceptors |
No built-in Axios-style interceptors. |
Supports request and response interceptors. |
| Best use |
Simple requests and browser-native functionality. |
Applications that benefit from its extra HTTP-client features. |
16. Best Practices for Using Fetch in React
- Check
response.ok before treating the response as successful.
- Handle network errors and invalid response bodies.
- Use loading, error, success, and empty states.
- Use
async/await or Promise chaining consistently.
- Use
useEffect when synchronizing with external data as appropriate, and declare all reactive dependencies.
- Use an event handler for requests directly triggered by user actions.
- Clean up obsolete requests when necessary.
- Use stable keys when rendering arrays.
- Avoid exposing API secrets in client-side code.
- Use caching and request-deduplication tools when appropriate for larger applications.
- Do not assume every successful HTTP response contains a JSON body; some responses, such as 204 No Content, have no body to parse.
17. Performance and Modern Data Fetching
Manual Fetch calls are useful for learning and small applications, but larger projects may need caching, request deduplication, preloading, and background revalidation.
- React frameworks: Use supported framework data-loading features where suitable.
- TanStack Query: Helps manage server state, caching, and refetching.
- SWR: Provides caching and revalidation features.
- React Router: Provides data-loading capabilities in supported versions.
- Pagination: Load records in smaller groups instead of requesting a huge dataset at once.
- Debouncing: Reduce unnecessary search requests while users type.
These are optional approaches. React itself does not automatically cache every Fetch request or deduplicate all requests.
18. Practical Project: Fetch and Display Posts
Project objective: Create a React component that fetches blog posts from a public API and displays their titles and descriptions.
Project Requirements
- Create a component called
PostList.
- Fetch data from
https://jsonplaceholder.typicode.com/posts.
- Store the retrieved posts in state.
- Display a loading message while the request is running.
- Show an error message if the request fails.
- Render each post's title and body.
- Use
post.id as the list key.
- Add a button to reload the posts.
- Test the component with a failed request and an empty result.
Expected Output
Blog Posts
------------------------------
Post 1 Title
Post description appears here...
Post 2 Title
Post description appears here...
Post 3 Title
Post description appears here...
The displayed content is illustrative. The actual titles and descriptions should come from the API response.
19. Interview Questions and Answers
Q1. What is the Fetch API?
The Fetch API is a browser feature that allows JavaScript to make network requests and process responses using Promises.
Q2. What does fetch() return?
It returns a Promise that usually fulfills with a Response object when the server responds.
Q3. Why do we use response.json()?
It reads the response body and parses it as JSON, returning a Promise for the parsed data.
Q4. Does Fetch reject its Promise for HTTP 404 or 500?
No. It normally fulfills with a Response object for these HTTP statuses. Check response.ok or response.status to detect unsuccessful responses.
Q5. What is the purpose of async/await?
It provides a more readable way to work with Promises and write asynchronous operations in a sequential style.
Q6. Why is Fetch often used with useEffect?
useEffect can synchronize a component with an external API when the component is displayed or its dependencies change.
Q7. What is AbortController?
It provides a way to cancel supported operations, including Fetch requests, through an associated AbortSignal.
Q8. What is CORS?
CORS is a browser security mechanism that controls whether a page can read resources from another origin.
Q9. How can we send JSON data in a POST request?
Specify method: "POST", set the appropriate content-type header, and convert the JavaScript object to a JSON string using JSON.stringify().
Q10. When should we consider a data-fetching library?
Consider one when the application needs features such as caching, automatic refetching, request deduplication, or coordinated server-state management.
20. Practice Exercises
- Fetch all users and display their names and email addresses.
- Fetch a single post by its ID.
- Create a POST request that submits a new post.
- Update a post using PUT and PATCH requests.
- Send a DELETE request to a demonstration API endpoint.
- Build a component with loading, error, success, and empty states.
- Cancel a request when a component's selected ID changes.
- Build a search box that filters fetched records.
- Compare Fetch and Axios for the same API endpoint.
21. Quick Revision
| Concept |
Remember |
fetch() |
Starts a network request and returns a Promise. |
response.ok |
Checks whether the HTTP status is successful. |
response.json() |
Parses the response body as JSON. |
async/await |
Makes Promise-based code easier to read. |
useState |
Stores data and request status in a component. |
useEffect |
Can synchronize a component with an external API. |
AbortController |
Can cancel a Fetch request. |
JSON.stringify() |
Converts a JavaScript value into JSON text. |
22. Official Documentation and Learning Resources
Conclusion
The Fetch API is an important tool for connecting React applications to external APIs. Understanding HTTP methods, Promises, response parsing, error handling, loading states, and request cancellation helps you build reliable and interactive applications. Practise with public APIs first, then apply these techniques to your own backend services.
Continue learning with JustAcademy React JS Training or Register for React JS Course Demo.