Back to Course

Learn React

0% Complete
0/0 Steps
Lesson 21 of 32
In Progress

Fetching Data from an API

One of the most common tasks when working with a web application is fetching data from an API. In this article, we’ll cover how to fetch data from an API using React.

Using the Fetch API

The fetch API is a built-in JavaScript method that allows us to make HTTP requests to an API. It’s a modern way of making network requests and is supported by most modern browsers.

Here’s an example of how we can use the fetch API to get data from an API:

fetch('https://api.mydomain.com/endpoint')
  .then(response => response.json())
  .then(data => {
    // do something with the data
  });

The fetch method returns a Promise that resolves to the response of the request. We can then use the json method on the response to get the data in JSON format.

Using async/await

Another way of handling the response from the fetch API is to use async/await. Async/await is a syntax for writing asynchronous code that makes it look like synchronous code.

Here’s an example of how we can use async/await to get data from an API:

async function getData() {
  const response = await fetch('https://api.mydomain.com/endpoint');
  const data = await response.json();
  // do something with the data
}

Fetching Data in a React Component

Now that we know how to fetch data from an API, let’s see how we can use this in a React component.

First, we need to create a component that will be responsible for fetching the data. This could be a function component or a class-based component.

In this example, we’ll create a function component called DataFetcher.

import React, { useState, useEffect } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://api.mydomain.com/endpoint');
      const data = await response.json();
      setData(data);
    }

    fetchData();
  }, []);

  return (
    <div>
      {data ? (
        <div>
          {data.map(item => (
            <div key={item.id}>{item.name}</div>
          ))}
        </div>
      ) : (
        <div>Loading...</div>
      )}
    </div>
  );
}

In this component, we’re using the useState and useEffect Hooks to fetch the data and store it in the data state. The useEffect Hook is called when the component mounts, and it makes the API request.

We’re also using a ternary operator to check if the data has been fetched. If it has, we render the data, if not, we render a loading message.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Write a function that fetches a list of users from the JSONPlaceholder API (https://jsonplaceholder.typicode.com/users) and console.logs the first user’s name.

const fetchUsers = () => {
  fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(users => console.log(users[0].name))
    .catch(error => console.error(error));
}

fetchUsers();

Modify the function from exercise 1 to set the list of users in state and display them in a list in the component.

const UserList = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(users => setUsers(users))
      .catch(error => console.error(error));
  }, []);

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

Write a function that makes a POST request to the JSONPlaceholder API to create a new user. The function should accept a name and email as arguments and include them in the request body.

const createUser = (name, email) => {
  fetch('https://jsonplaceholder.typicode.com/users', {
    method: 'POST',
    body: JSON.stringify({ name, email }),
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then(response => response.json())
    .then(user => console.log(user))
    .catch(error => console.error(error));
}

createUser('John', 'john@example.com');

Write a function that makes a DELETE request to the JSONPlaceholder API to delete a user with a given ID. The function should accept an ID as an argument and include it in the request URL.

const deleteUser = id => {
  fetch(`https://jsonplaceholder.typicode.com/users/${id}`, {
    method: 'DELETE'
  })
    .then(response => response.json())
    .then(user => console.log(user))
    .catch(error => console.error(error));
}

deleteUser(1);

Write a function that fetches data from an API and returns the data as a string.

function fetchData() {
  return fetch('https://api.example.com/endpoint')
    .then(response => response.json())
    .then(data => data.toString())
}