Fetching API Data in React Using Fetch and Axios

Tutorial 1 of 5

1. Introduction

Goal

The goal of this tutorial is to guide you on how to fetch data from an API in a React application using two popular methods: Fetch and Axios.

Learning Outcomes

  • Understand how to use Fetch and Axios library to fetch data from an API in a React application.
  • Learn how to handle responses and manage errors during the data fetching process.

Prerequisites

  • Basic understanding of JavaScript and React.
  • Node.js and npm installed on your local development machine.
  • A text editor, such as Visual Studio Code.

2. Step-by-Step Guide

Fetch API

Fetch is a built-in browser API for making HTTP requests. It's promise-based, and it's a great option for simple requests. However, it's not supported in Internet Explorer.

Axios

Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js. It has a number of advantages over Fetch, such as the ability to automatically transform JSON data.

3. Code Examples

Using Fetch

// Import react and useState, useEffect hooks
import React, { useState, useEffect } from 'react';

const FetchExample = () => {

  const [data, setData] = useState([]);

  // Use useEffect to call the API once the component has mounted
  useEffect(() => {
    fetch('https://api.example.com/items')
      .then(response => response.json())
      .then(data => setData(data)); 
  }, []);

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

export default FetchExample;

In this example, we are fetching data from 'https://api.example.com/items' URL. The fetched data is then converted to JSON format using response.json(). The JSON data is saved in the data state variable using setData function.

Using Axios

// Import react, useState, useEffect hooks, and axios
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const AxiosExample = () => {

  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get('https://api.example.com/items')
      .then(response => {
        setData(response.data);
      })
      .catch(error => console.error(`Error: ${error}`));
  }, []);

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

export default AxiosExample;

In the Axios example, we are doing the same thing but with the Axios library. The advantage here is that Axios automatically converts the response data into JSON, so we don't have to call .json() as with fetch. Also, Axios provides a simple way to catch and handle errors.

4. Summary

  • We have learned how to fetch data from an API using the Fetch API and Axios in a React application.
  • We have also learned how to handle responses and manage errors during the data fetching process.

5. Practice Exercises

  1. Fetch data from the following API endpoint using Fetch and Axios: 'https://jsonplaceholder.typicode.com/posts'.
  2. Handle the data response and display the title of each post in a list.
  3. Add error handling to the data fetch operation.

Next Steps

  • Learn more about Fetch and Axios.
  • Practice fetching data from different API endpoints and displaying the data in different ways.

Additional Resources