menu

Questions & Answers

API Call only works on homepage but not subpage?

I'm relatively new working with promises in JS. I got the API call to work on the initial homepage, but I'm having issues when I go to another page that is using the same API call.

In my api.js file I have the following:

const key = apiKey;
const commentsUrl = axios.get(`https://project-1-api.herokuapp.com/comments/?api_key=${key}`);
const showsUrl = axios.get(`https://project-1-api.herokuapp.com/showdates?api_key=${key}`);

async function getData() {
    const allApis = [commentsUrl, showsUrl];

    try {
        const allData = await Promise.allSettled(allApis);

        return allData;
    } catch (error) {
        console.error(error);
    }
}

In my index.html

import { getData } from "./api.js";

let data = await getData(); //This works and gathers the data from the API.

In my shows.html

import { getData } from "./api.js";

let showsData = await getData(); //This does not and says that cannot access commentsUrl (api.js) before it is initialized. But it is? 

If I comment out the code from "show", the API GET request works fine and the index page loads the API data correctly. Can anyone explain to me what's happening and why I would be getting the uninitialized error?

I also should note that if I split the API calls onto two seperate two js files (one for the index, one for the shows), the API calls works and displays the data as it is intended to.

Comments:
2023-01-22 23:10:13
Gave that a shot but no dice.
2023-01-22 23:10:13
Aren't you using those axios calls wrong? You should have a function that returns the promise, e.g. var myApi = function() { return axios.get('...'); }
Answers(1) :

On the homepage, the code is executing the 2 GET requests on page load/initialization of the JS code. When you navigate away from the homepage, presumably with some sort of client-side routing, the 2 GET requests no longer reference 2 Promises as they have already been executed.

You could instead move the GET requests into your function like:

const key = apiKey;

async function getData() {
    try {
        const commentsUrl = axios.get(`https://project-1- api.herokuapp.com/comments/?api_key=${key}`);
        const showsUrl = axios.get(`https://project-1-api.herokuapp.com/showdates?api_key=${key}`);
        const allApis = [commentsUrl, showsUrl];
        const allData = await Promise.allSettled(allApis);

        return allData;
    } catch (error) {
        console.error(error);
    }
}
Comments:
2023-01-22 23:10:13
Unfortunately, I tried this and I'm still having the same issue.