Fetching Data Using Fetch API
In this lesson, you will learn how to request data from an API using JavaScript's Fetch API, understand HTTP responses, process JSON data, and handle basic request errors in a React application.
1. What Is the Fetch API?
The Fetch API is a built-in JavaScript feature used to make HTTP requests to servers and other web resources. It allows a React application to retrieve information from an API without installing an additional HTTP library.
For example, a student management application may request a list of students from a backend API and then display the returned information on the page.
Why Use Fetch API?
- It is built into modern browsers.
- It supports HTTP methods such as GET and POST.
- It returns a Promise that can be handled using
.then()orasync/await. - It can read JSON responses from an API.
- It can be used with React state and effects to display remote data.
fetch().
2. How Fetch API Works
Fetch sends a request to the specified URL. The server returns an HTTP response. The application then checks the response, reads the body in the required format, and uses the resulting data.
- Specify the API endpoint.
- Call
fetch()to send the request. - Check whether the HTTP response indicates success.
- Read the response body using
response.json(). - Use the parsed data in the application.
3. Making a Basic GET Request
A GET request is commonly used to retrieve information from an API. The following example uses JSONPlaceholder, a public test API.
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => {
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
Explanation
-
fetch(url)sends a GET request by default. -
responsecontains the HTTP status and response information. -
response.okis true for HTTP status codes from 200 through 299. -
throw new Error()moves execution to the error handler when the response is unsuccessful. -
response.json()reads and parses the response body as JSON. -
console.log(data)displays the parsed result in the browser console. -
catch()handles rejected requests and errors thrown in the preceding Promise chain.
response.ok when
unsuccessful HTTP responses need to be handled as errors.
4. Understanding the API Response
The example endpoint returns an array of user objects. Each object contains properties such as an ID, name, username, email, and address.
[
{
"id": 1,
"name": "Leena",
"username": "leena123",
"email": "leena@example.com"
},
{
"id": 2,
"name": "Samiksha",
"username": "samiksha123",
"email": "samiksha@example.com"
}
]
This is an illustrative sample of the response structure. The actual values returned by the endpoint may be different.
After parsing the response, JavaScript can access properties
using expressions such as data[0].name or
data[0].email.
Example Values
First user's name: data[0].name
First user's email: data[0].email
Second user's name: data[1].name
5. Using Fetch API in a React Component
In React, API data is usually stored in state so that the
component can display it. The useState Hook stores
the users, and useEffect starts the request when the
component is mounted.
This example introduces the basic integration of Fetch with React. Loading and error UI will be covered in more detail in a later lesson.
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => {
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
})
.then(data => {
setUsers(data);
})
.catch(error => {
console.error("Error fetching users:", error);
});
}, []);
return (
<div>
<h2>Users List</h2>
<ul>
{users.map(user => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
</div>
);
}
export default Users;
Step-by-Step Explanation
-
useState([])creates a state variable nameduserswith an empty array as its initial value. -
useEffect()runs the effect after the component has been rendered. -
The empty dependency array
[]means the effect is scheduled to run after the initial mount. - Fetch requests the user data from the API.
-
setUsers(data)stores the parsed response in React state. -
users.map()creates a list item for each user. -
key={user.id}provides React with a stable key for each list item.
6. Why Use useEffect for API Requests?
Fetching data is a side effect because it involves communication
with an external system. The useEffect Hook is
commonly used to start a request when a component is mounted or
when selected dependencies change.
useEffect(() => {
// Start an API request here
}, []);
- Empty dependency array: The effect is scheduled after the initial mount.
- Dependencies included: The effect can run again when a dependency changes.
- No dependency array: The effect runs after every render, which may cause repeated requests if used carelessly.
7. Fetch API vs React State
Fetch and state have different responsibilities. Fetch retrieves information from the server, while React state stores the data that the component uses to render its interface.
- Fetch API: Sends the HTTP request.
- response.json(): Parses the response body.
- useState: Stores the data in the component.
- setUsers(data): Updates the stored data.
- users.map(): Renders the user records.
8. Common Mistakes
- Forgetting response.json(): The response body must be parsed before using JSON data.
-
Ignoring HTTP errors: Check
response.okbecause a 404 or 500 response does not automatically reject the Fetch Promise. - Not handling rejected requests: Use error handling for network failures and parsing errors.
-
Updating state incorrectly: Use the state
setter such as
setUsers(data). -
Missing list keys: Give mapped elements stable
keys such as
user.id. - Putting fetch directly in the render body: This may trigger repeated requests on every render. Use an appropriate Effect or event handler instead.
9. Practice Tasks
Task 1: Fetch User Data
Write a Fetch request to retrieve data from
https://jsonplaceholder.typicode.com/users
and display the result in the browser console.
Task 2: Display User Names
Create a React component that fetches users and displays only
their names using map().
Task 3: Display Emails
Modify the component to display each user's name and email address in a list.
Task 4: Check the Response
Add a check for response.ok and throw an error
when the HTTP response is unsuccessful.
Task 5: Fetch Posts
Use https://jsonplaceholder.typicode.com/posts
to retrieve posts and display their titles in a React component.
Summary
In this lesson, you learned how to make GET requests using the Fetch API, inspect HTTP responses, check response.ok, parse JSON data, and handle errors with Promise methods. You also learned how to combine Fetch with useEffect and useState to retrieve and display user records in a React component. In the next lesson, you will explore asynchronous JavaScript using async and await to make API request code easier to read.