Kinda Code
Home/React/How to fetch data from APIs with Axios and Hooks in React

How to fetch data from APIs with Axios and Hooks in React

Last updated: March 03, 2023

Introduction

Fetching data (sending GET requests) is one of the most common stuff in React development. In this tutorial, you’ll learn how to use the useState hook, the useEffect hook, and Axios to fetch JSON format data from the internet then display them on the screen.

In this article, we’ll use the following open REST API endpoint:

https://jsonplaceholder.typicode.com/posts

This API provides 100 dummy blog posts. A single blog post has the structure like this:

{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},

The Steps

1. Create a brand new React app:

npx create-react-app my_app

2. Install the Axios library by running the following command in your project root:

npm i axios

or:

yarn add axios

3. Remove all the default code in src/App.js and add this:

// App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';

import './App.css';

// The REST API endpoint
const API_URL = 'https://jsonplaceholder.typicode.com/posts';

const App = () => {
  // At the beginning, posts is an empty array
  const [posts, setPosts] = useState([]);

  // Define the function that fetches the data from API
  const fetchData = async () => {
    const { data } = await axios.get(API_URL);
    setPosts(data);
  };

  // Trigger the fetchData after the initial render by using the useEffect hook
  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className="wrapper">
      {posts.length > 0 ? (
        <div className="content">
          {posts.map((post) => (
            <div className="post">
              <h2>{post.title}</h2>
              <p>{post.body}</p>
            </div>
          ))}
        </div>
      ) : (
        <p className="loading">Loading... </p>
      )}
    </div>
  );
};

export default App;

4. Remove the pre-made code in src/App.css the add some styles to make our app more attractive:

.wrapper {
  padding: 30px; 
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  max-width: 480px;
}

.post {
  padding: 25px 0;
  border-bottom: 1px solid #ccc;
}

.loading {
  text-align: center;
}

Now, let’s check it out:

Final Words

We’ve walked through an end-to-end example of fetching data with hooks and Axios. If you would like to explore more exciting stuff about React, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Related Articles