Consuming APIs in React: Axios vs Fetch

React is a popular JavaScript library designed specifically for building front-end interfaces. at a point in our development journey, they'll be a need to communicate and share resources to and from the backend.

Communications between the front-end and backend happen via consuming APIs using the fetch() method or Axios.

API

API stands for "Application Programming Interface", it is a program that acts as an intermediary between two applications to communicate and share resources. APIs lay the floor for developers to slide in new resources into existing components.

API Operations:

Operations that can be done with APIs are classified into four parts namely:

  • Create

  • Read

  • Update and

  • Delete

short for CRUD, which are then embedded into HTTP Request methods namely:

  • Post: to create a resource

  • Get: to read or request data

  • Put: to update data or resources

  • Delete: to delete data from the server.

Fetch

The fetch() method is a built-in functionality that is defined on the window object. no installation is needed to access or use it.

Axios

Axios is a third-party package designed for consuming APIs fast and efficiently. installation is needed to be able to use it.

//installation with npm package.

npm install axios@latest.

Both fetch and Axios are used for consuming APIs to get resources from the backend that'll then return a promise.

One of two things happens when fetching resources from an API endpoint.

  • it's either the request is successful, which is referred to as "Resolved" or

  • the request failed, which then returns an error.

-this concept is called Promise.

Consuming APIs in React

In React, consuming APIs is the process of sending requests to the backend server using a specific URL endpoint.

in React, it's highly advisable that our functions should always be pure functions. A pure function should not have any side effects, and should always return the same result with the same input.

in React, consuming APIs naturally causes side effects to our component, which directly means it's unpure. to purify our code and rid it of side effects, we'll make use of the Effect Hook (useEffect).

Effect Hook

The effect hook is used to execute a piece of code after a component is rendered.

we'll also make use of the State Hook (useState) .

State Hook

The state hook is used will be used to store the requested data from the backend. get more insights about state hooks here.

we'll need both the useEffect and UseState hooks to consume APIs in React.

Using the Fetch Method

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

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

    useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/users")
        .then(response => json.response())//to convert the response to json.
        .then(data => setUsers(data))//to store the data got to the state function.
        .catch(err => console.log(err))//to log error to the console.
    },[])

return (
// display the data here...
)
}

Using Axios

import axios from 'axios'
import {useState} from 'react'
import {useEffect} from 'react'

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

    useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/users")
    .then(response => setusers(response.data))
    .catch(error => setUsers(error))
})

Async / Await

Asyn and Await are used in combination to handle asynchronous operations.

asynchronous operations basically are tasks that don't happen immediately but rather take some time to complete.

the rest of the code can continue executing while the asynchronous task is in progress - this concept is called "non-blocking".

using async/await allows us to turn asynchronous operations into synchronous ones.

to use the async/await functions we have to get rid of the .then method and wrap our code within the try/catch block.

Using Async/Await with the Fetch Method

import axios from 'axios'
import {useState} from 'react'
import {useEffect} from 'react'

const App = () => {
    const [users, setUsers] = useState([]);
    const [error, setError] = useState('');

    useEffect(() => {
    const fetchUsers = async () => {
        try {
            const response = await fetch
               ("https://jsonplaceholder.typicode.com/users");
                const data = await response.json();
                console.log(data)
                setusers(data)
        }
        catch (error) {
            setError(error)
        }
    }
    fetchUsers();
},[])

Using Async/Await with Axios

import axios from 'axios'
import {useState} from 'react'
import {useEffect} from 'react'

const FetchData = () => {
    const [users, setUsers] = useState([]);
    const [error, setError] = useState('');

    useEffect(() => {
    const fetchUsers = async () => {
        try {
            const response = await axios
            .get("https://jsonplaceholder.typicode.com/users");
            setusers(response.data)
        }
        catch (error) {
            setError(error)
        }
    }
    fetchUsers();
},[])

Differences and Similarities

Fetch is pre-installedAxios have to be installed
Fetch has to be converted to JSON formatAxios format to JSON automatically
Fetch cannot intercept HTTP RequestsAxios can intercept HTTP Requests
Fetch has no protectionAxios has a protection called XSRF
Fetch has no ability to cancel requestsAxios can cancel requests

Conclusion

With the above, I believe you've had a better view of consuming APIs in React, the better, faster, and safer approach to employ when working with APIs.