Displaying API Data in React
In this lesson, you will learn how to retrieve API data, store it in React state, display records using JSX, render lists with map(), and use unique keys for list items. You will also understand how to handle empty data and structure API results into readable user interfaces.
1. What Does Displaying API Data Mean?
When a React application requests data from an API, the server typically returns information in a format such as JSON. The application can store that information in state and use JSX to display it on the page.
For example, a training institute website may request course details from an API and display the course name, duration, and description in separate cards.
Basic Process
2. Understanding the API Response
Before displaying API data, understand the structure of the response. An API may return an array of objects, with each object representing one record.
[
{
"id": 1,
"name": "Samadhan",
"email": "samadhan@example.com"
},
{
"id": 2,
"name": "Samiksha",
"email": "samiksha@example.com"
},
{
"id": 3,
"name": "Rahul",
"email": "rahul@example.com"
}
]
Here, the response is an array containing three objects. Every
object has an id, a name, and an
email property.
data[0].nameaccesses the first user's name.data[1].emailaccesses the second user's email.data.lengthreturns the number of records in the array.
3. Store API Data Using useState
React's useState Hook lets a component store values
that may change over time. When API data arrives, the state setter
updates the state and React renders the component again.
import { useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
return (
<div>
<h2>Users List</h2>
<p>Total users: {users.length}</p>
</div>
);
}
export default Users;
Explanation
useState([])initializes the state with an empty array.userscontains the current array of users.setUsersupdates the state.users.lengthprovides the current number of users.
4. Fetch API Data and Display It
The following example retrieves users from JSONPlaceholder and
displays their names and email addresses. The request runs in
useEffect, while the returned records are stored
in state.
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
async function fetchUsers() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const data = await response.json();
setUsers(data);
} catch (error) {
console.error("Error fetching users:", error);
}
}
fetchUsers();
}, []);
return (
<div>
<h2>Users List</h2>
<ul>
{users.map(user => (
<li key={user.id}>
<strong>{user.name}</strong>
{" - "}
{user.email}
</li>
))}
</ul>
</div>
);
}
export default Users;
How the Code Works
- The component starts with an empty users array.
- The Effect starts the API request after the component mounts.
- The response is checked using
response.ok. - The JSON response body is parsed into JavaScript data.
setUsers(data)stores the returned records in state.- React renders the list using the updated state.
5. Display Multiple Records Using map()
The map() array method creates a new array by applying
a function to each item in the original array. In React, it is
commonly used to render a list of components or JSX elements.
const courses = [
{ id: 1, name: "React" },
{ id: 2, name: "Angular" },
{ id: 3, name: "Node.js" }
];
function CourseList() {
return (
<ul>
{courses.map(course => (
<li key={course.id}>
{course.name}
</li>
))}
</ul>
);
}
export default CourseList;
Expected Output
Course List
- React
- Angular
- Node.js
The example uses local sample data to demonstrate rendering. The same pattern works when the array comes from an API.
6. Why Is the key Prop Important?
When React renders a list, each sibling element should have a stable and unique key. The key helps React identify which items have changed, been added, or been removed.
{users.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
Important Points
- Use a unique, stable identifier such as the record ID.
- Keys should be unique among siblings in the rendered list.
- Avoid generating a new random key on every render.
- Array indexes are usually not ideal when items can be reordered, inserted, or deleted.
key is used by React during reconciliation. It
is not automatically passed to the child component as a normal prop.
7. Display API Data in Cards
Lists are useful for simple records. Cards are another way to organize information when each record contains multiple fields. For example, a course card can show the course name, duration, and description.
const courses = [
{
id: 1,
name: "React",
duration: "6 Weeks",
description: "Learn React components and Hooks."
},
{
id: 2,
name: "Node.js",
duration: "8 Weeks",
description: "Learn server-side JavaScript."
}
];
function CourseCards() {
return (
<div>
<h2>Available Courses</h2>
{courses.map(course => (
<article key={course.id}>
<h3>{course.name}</h3>
<p>Duration: {course.duration}</p>
<p>{course.description}</p>
</article>
))}
</div>
);
}
export default CourseCards;
This example uses local data to demonstrate the layout. In a real application, you can replace the local array with API data stored in React state.
8. Handle Empty API Data
An API may return an empty array when no records are available. Rather than showing a blank list, the application can display a helpful message.
{users.length === 0 ? (
<p>No users available.</p>
) : (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
)}
9. Common Mistakes
-
Not parsing the response: Use
response.json()when the API returns JSON. - Rendering before data arrives: Initialize state with a suitable value such as an empty array.
- Forgetting list keys: Add a stable key to each mapped list item.
- Accessing missing properties: Confirm that the API response contains the property names your JSX uses.
-
Ignoring HTTP errors: Check
response.okbefore using the response body. - Updating state directly: Use a state setter instead of modifying the current array in place.
10. Practice Tasks
Task 1: Display User Names
Fetch users from
https://jsonplaceholder.typicode.com/users
and display their names in an unordered list.
Task 2: Display User Details
Display each user's name, email, and username using separate JSX elements.
Task 3: Create Course Cards
Create course objects containing an ID, name, duration, and description. Display each course using a card-style layout.
Task 4: Show an Empty Message
Display "No records available" when the array is empty and render the list when records exist.
Task 5: Understand Keys
Render an API array using map() and assign a
stable unique key to each list item.
Summary
In this lesson, you learned how to display API data in React, understand JSON arrays and objects, store records with useState, retrieve information using Fetch and useEffect, and render lists with map(). You also learned why stable keys are important, how to display records in cards, and how to handle empty data. In the next lesson, you will learn how to manage loading and error states so users receive clear feedback while API requests are in progress or fail.