API Calls
Fetching data from an external server or API and displaying it in React.
Learning Goals
The Core Concept
Almost all real-world applications need to fetch external data. In React, we combine `useState` (to store the fetched data) and `useEffect` (to trigger the fetch operation when the component loads). We typically use the native browser `fetch` API or a library like `axios`. It is important to handle different states during an API call: a loading state, an error state, and the successful data state.
Visual guide
React concept flow
A simple original diagram to connect the lesson idea with real project flow.
Code & Implementation
import { useState, useEffect } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => {
setUsers(data);
setIsLoading(false);
});
}, []);
if (isLoading) return <p>Loading users...</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Expected Output
- Leanne Graham - Ervin Howell - Clementine Bauch
Movie Finder
Hands-on practice task
The Challenge
Create an application that searches a public API for movies and displays a grid of movie posters and titles.
Helpful Hints
- •Use a free API like OMDB API. You will need to register for a free API key.
- •Create an input field for the search term.
- •When the user clicks 'Search', fetch the data based on the input term and update your movies array state.
Quick Knowledge Check
Can I make the useEffect callback function async?
Continue Learning
Next steps after this lesson
Create an application that searches a public API for movies and displays a grid of movie posters and titles.
Supercharge your career workflows!
Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.