T

TechIdea

Ecosystem

Reactintermediate10 min read

API Calls

Fetching data from an external server or API and displaying it in React.

Learning Goals

1
Understand the purpose and application of API Calls in React projects.
2
Implement clean, functional code demonstrating API Calls syntax.
3
Identify and avoid common coding mistakes associated with api calls.
4
Apply API Calls features to solve a realistic intermediate-level development task.

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

react
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

Required for Mastery

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?
No, the callback function directly inside useEffect cannot be async. Instead, define an async function inside the effect and immediately call it.

Continue Learning

Next steps after this lesson

Practice task

Create an application that searches a public API for movies and displays a grid of movie posters and titles.

Ready to take action?

Supercharge your career workflows!

Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.

Growth Newsletter

Get practical AI tools, SEO tips, and growth guides weekly.

Join creators, students, and businesses scaling with TechIdea.