ScanSkill
Sign up for daily dose of tech articles at your inbox.
Loading

Concurrent API Requests using Promise.all() in React

Concurrent API Requests using Promise.all() in React
Concurrent API Requests using Promise.all() in React

In this article, we will discuss how to perform concurrent API requests using Promise.all() in React. Concurrent means handling more than one task at a time. Promise.all() is a method that takes an array of promises and returns a single promise when all the passed-in promises are resolved. If any of the promises get failed then the Promise.all() method asynchronously rejects the value of all the promises even if other promises have been resolved. 

Prerequisites

Syntax

Promise.all([promise1, promise2, promise3]);

Example

import React, { useState } from "react";
import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  const [result, setResult] = useState([]);

  const handleApiCall = async () => {
    try {
      const response = await Promise.all([
        axios.get("https://jsonplaceholder.typicode.com/posts/1"),
        axios.get("https://jsonplaceholder.typicode.com/posts/2"),
        axios.get("https://jsonplaceholder.typicode.com/posts/3"),
      ]);
      console.log("response",response)
      const data = await Promise.all(response.map((res) => res.data));
      setResult(data);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className="m-4">
      <button className="btn btn-primary" onClick={handleApiCall}>
        Call Api
      </button>
      <br/>
      <span>Result</span>
      <br/>
      {result.map((item) => (
        <div className="my-2" key={item.id}>
          <strong>{item.title}</strong>
          <p>{item.body}</p>
        </div>
      ))}
    </div>
  );
}

Here, we can see an example of requesting 3 get APIs concurrently from a dummy API provider site https://jsonplaceholder.typicode.com when a button is clicked. Those 3 APIs are requested concurrently using Promise.all(). axios.get() function is used to request the get API for 3 separate paths. async/await function is used along with Promise.all() method. async/await are the keywords when used in pair properly makes a particular function an asynchronous data acceptor.

Output

Concurrent API Requests using Promise.all() in React

Here, we can see all the 3 API requests are handled concurrently. Promise for all the passed-in requests are successfully resolved and hence it returns a single promise and returns data of all the corresponding API requests. Then, All the received data are stored as an array using useState hook and then, the title and description from the stored data are displayed as a list using map() method.

Conclusion

In this article, we discussed how to perform concurrent API requests using Promise.all() in React. In the example, we requested 3 get APIs for 3 different paths and then displayed the result in the react app.

Sign up for daily dose of tech articles at your inbox.
Loading