Steve Sultan
Steve Sultan's Blog

Steve Sultan's Blog

How to send multiple requests using axios?

Steve Sultan's photo
Steve Sultan
·Jan 25, 2022·

3 min read

Subscribe to my newsletter and never miss my upcoming articles

Let us begin with a simple operation and submit one request using Axios. First, we import axios and specify the API/URL from which we want to load data.

import axios from 'axios';

let one = "https://api.abc.com/ex"

Following that, we specify that we wish to make a GET request to the above URL using axios.

const requestOne = axios.get(one);

We now have an unresolved promise in requestOne that we can utilise to finally perform the GET request and receive the response.

requestOne.then(response => {
  console.log(response)
}).catch(error => {
  console.err(error)
})

Because axios delivers a Promise, we can use Promise.all to handle numerous requests. all, fortunately, axios comes with a function named all, so let us use that instead and add two more requests.

Again, we provide the URLs we wish to access.

import axios from 'axios';

let endpoints =  [  
    'https://api.github.com/users/ejirocodes',
    'https://api.github.com/users/ejirocodes/repos', 
    'https://api.github.com/users/ejirocodes/followers',  
    'https://api.github.com/users/ejirocodes/following'  ];

   axios.all(endpoints.map((endpoint)  => axios.get(endpoint)))
   .then( axios.spread((
   {data: user},  
   {data:repos},  
   {data:followers},  
   {data:following})  =>  
   { console.log({ user, repos, followers, following });  })  );

Promise.all vs. axios.all

The Promise.all method returns a promise that resolves when all of the promises in the iterable argument resolve.

Now, let’s see this in action:

let endpoints =  [  
      'https://api.github.com/users/ejirocodes',
      'https://api.github.com/users/ejirocodes/repos',  
      'https://api.github.com/users/ejirocodes/followers', 
      'https://api.github.com/users/ejirocodes/following'  ]; 

    // Return our response in the allData variable as an array 
     Promise.all(endpoints.map((endpoint)  => 
     axios.get(endpoint)))
     .then( axios.spread((...allData)  =>  
     { console.log({ allData });  })  );

Concurrent API requests in React with Promise.all and Axios

To make simultaneous API requests in a React app using Axios and Promise, we must use React Hooks.

In this example, we will get both the followers and following data of a GitHub profile. The idea is that, if for some reason, the API request for the followers data for the user’s GitHub profile is unsuccessful, we can’t get the response for the followers data for the user’s GitHub profile.

This means the request for the user’s GitHub user profile follwing count will also fail.

This is because when we make concurrent requests, the response from one request depends on the other. So, essentially, we want both or all requests to fail if at least one fails.

Using Promise.all and ES6 destructuring, let’s write a function that will perform multiple GET requests concurrently in our React app:

// In our component, we have to save both 
//data in our state using the useState hook  const 
 [followers, setFollowers]  = useState([])  
 const  [followings, setFollowing]  = useState([])  
 const getGithubData =  ()  =>  {  let endpoints =  [  
  'https://api.github.com/users/ejirocodes',  
  'https://api.github.com/users/ejirocodes/repos', 
  'https://api.github.com/users/ejirocodes/followers', 
  'https://api.github.com/users/ejirocodes/following'  ];  
   Promise.all(endpoints.map((endpoint)  => 
   axios
   .get(endpoint)))
   .then(([
   {data: user},  
   {data: repos}, 
    {data: followers},  
    {data: followings}]  )
    =>  { setFollowers(followers) setFollowing(followings)  });  }

Next, let’s call the function when the page loads. To achieve this the React way, we’ll use theuseEffect Hook:

// remember to import useEffect from react 
useEffect(()  =>  { 
    getGithubData();  
},  []);

Then, render both the followers and following data we just received from the various endpoints to the DOM:

// Wherever your return statement is in your React app

<section  style={{ display:  "flex" }}>

    <section>

        <h2>Followers</h2>

        {followers.length > 0 && (

        <div>

            {followers.map((follower) => (

            <div  key={follower.id}>

            <img  src={follower.avatar_url}  alt={follower.html_url}  />

            <p>GitHub Profile: {follower.html_url}</p>

        </div>

        ))}

        </div>

        )}

        </section>

        <section>

            <h2>Following</h2>

            {followings.length > 0 && (

            <div>

                {followings.map((following) => (

                <div  key={following.id}>

                    <img  src={following.avatar_url} 
                     alt={following.html_url}  />

                    <p>GitHub Profile: {following.html_url}</p>

                </div>

                ))}

            </div>

            )}

    </section>

</section>

Source: blog.logrocket.com/using-axios-all-make-con..

storyblok.com/tp/how-to-send-multiple-reque..

 
Share this