DEV Community

Cover image for Fetch multiple API requests in vanilla JS
sanderdebr
sanderdebr

Posted on

3 1

Fetch multiple API requests in vanilla JS

It is very common in Javascript to fetch some data from an API. But what if you want to fetch many requests and only perform actions when they are all are resolved? In this article I will explain briefly how to fetch data from an API in vanilla JS (ES6) and also how to handle MANY API requests.

First, let's start with a simple API fetch. I will wrap my function in an IIFE and only expose the init method, so that from the outside the function can not be controlled and our variables and methods our private.

Make sure to set the function to asynchronous by adding the async keyword. Also always wrap your fetches inside a try-catch block to avoid breaking your application and detecting what went wrong.

Also notice how I'm storing constant values in a seperate private object that we can access only inside our myApp function. Always try to structure data and keep it modular.

const myApp = (function() {
    const constants = {
        data: document.getElementById('data')
    }

    const fetchData = async () => {
        constants.data.innerText = 'fetching data...';
        try {
            const response = await fetch("https://pokeapi.co/api/v2/pokemon/1")
                             .then(response => response.json());
          data.innerText = response.name;
        } catch (error) {
            console.error(error);
        }
    }

    const init = () => {
        fetchData();
    }

    return {
        init: init
    }
})();

<div id="data"></div>

myApp.init();

Not too bad, right?

Now what if we want to fetch data from hundreds of API request and wait until they are all finished? We will do this using Promise.all() which will loop over an array of urls, in this case 25:

const myApp = (function() {  
    const fetchData = async () => {

        let urls = [];
        for (let i = 0; i < 25; i++) {
           urls.push('https://pokeapi.co/api/v2/pokemon/');
        }

        try {
            const response = Promise.all(urls.map((url, i) =>
                  fetch(url+i).then(resp => resp.json())
              )).then(json=> {
                  console.log(json)
              })
        } catch (error) {
            console.error(error);
        }
    }

    const init = () => {
        fetchData();
    }

    return {
        init: init
    }
})();

myApp.init();

Cool, right? Hope you've learned something, have fun fetching data from API's!

Here is a free list of API's you can play around with: https://apilist.fun/

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay