DEV Community

Cover image for How to consume APIs in React using Fetch and Axios with the Async Await syntax
Christian Ndu
Christian Ndu

Posted on

How to consume APIs in React using Fetch and Axios with the Async Await syntax

Good day lovely friend of the internet, You have probably come across the term API before maybe on Twitter, a developer slack/discord channel or heard someone mention it somewhere. In this article I'm going to explain to you what APIs are and how to consume them in Reactjs.

What are APIs?

A - Application, P - Programming, I - Interface(s)
A definition from Wikipedia goes like "An application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software."

In essence, APIs are a way to send and receive data from a client (frontend) to a server (backend)

Pre-requisites

Before going further in this article, I expect you to have forehand knowledge of React, React Hooks and Functional Components in React.
You do? Then lets Go!

Using Fetch

Fetch is a built-in JavaScript method that allows you to make API requests in client-side JavaScript. Its comes by default with JavaScript and you don't need to install anything to make use of it on the client side. Refer to the MDN page on Fetch to learn more.

Here's an example of a GET request

import { useState, useEffect } from "react";

export default function Post() {
    const [posts, setPosts] = useState([]);
    const url = "https://jsonplaceholder.typicode.com/posts";

    // We add the `async` keyword to enable the use of `await`
    const getPosts = async () => {
    // The `await` keyword ensures the request is fulfilled
        // before the result is returned
        try {
            const response = await fetch(url);
// The response is parsed to JSON so we can manipulate it easily
            const data = response.json();
            setPosts(data);
        } catch (error) {
            console.log(error);
        }
    };
    useEffect(() => {
        getPosts();
    }, []);
    return (
        <>
            {posts.map((post, index) => (
                <div key={index}>
                    <h1>{post.title}</h1>
                    <p>{post.body}</p>
                </div>
            ))}
        </>
    );
}

Enter fullscreen mode Exit fullscreen mode

Using Axios

Axios is an open-source JavaScript library. It is a Promise based HTTP client for the browser and node.js. You can learn more about it in the official documentation

First you need to install the package as a dependency in our application

using npm

npm install axios 
Enter fullscreen mode Exit fullscreen mode

using yarn

yarn add axios
Enter fullscreen mode Exit fullscreen mode
import { useState, useEffect } from "react";
import axios from "axios";

export default function Post() {
    const [posts, setPosts] = useState([]);
    const url = "https://jsonplaceholder.typicode.com/posts";

    const getPosts = async () => {
        try {
            const response = await axios(url);
            setPosts(response.data);
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        getPosts();
    }, []);
    return (
        <>
            {posts.map((post, index) => (
                <div key={index}>
                    <h1>{post.title}</h1>
                    <p>{post.body}</p>
                </div>
            ))}
        </>
    );
}

Enter fullscreen mode Exit fullscreen mode

In summary, we define the getPosts function and make it run only once which is when the component loads (this is done by passing an empty array of dependencies as useEffect's second argument, see how it works)

We also use try/catch to make our code more readable and to handle errors more efficiently.

The most notable differences between using Fetch and Axios is that you don't need to parse the response to JSON with Axios unlike Fetch and also that the Axios response isn't an array like Fetch but a JavaScript object where our actual data lies in a data key. To keep the article short and simple I only made GET requests but you can make other HTTP requests like POST, PUT, DELETE etc. using Fetch and Axios.

That's it!

Top comments (0)