Encountering an issue when executing a RapidAPI request using asynchronous functions

Help needed with API request error

I’m trying to make a GET request to RapidAPI but I’m running into a problem. The error message I’m getting is:

Uncaught (in promise) ReferenceError: Cannot access 'getData' before initialization

Here’s the code I’m using:

const API_KEY = process.env.MY_API_KEY;
const LOCATION_ENDPOINT = 'https://location-lookup.example.com/check?format=json';
const API_HOST = 'location-lookup.example.com';

const fetchLocationData = async (endpoint, host) => {
  const result = await fetch(endpoint, {
    method: 'GET',
    headers: {
      'accept': 'application/json',
      'x-api-host': host,
      'x-api-key': API_KEY
    }
  });

  if (!result.ok) {
    throw new Error(`Request failed with status: ${result.status}`);
  }

  return await result.json();
};

const executeApiCalls = async () => {
  const fetchLocationData = await fetchLocationData(LOCATION_ENDPOINT, API_HOST);
  console.log(fetchLocationData);
};

executeApiCalls();

Can anyone spot what I’m doing wrong? Thanks in advance for any help!

hey there! looks like u might be running into a scoping issue. try renaming ur fetchLocationData function inside executeApiCalls to something else, like getLocationData. that way it won’t clash with the outer function name. hope this helps ya out!

The issue you’re facing is a classic case of variable shadowing. In your executeApiCalls function, you’re declaring a variable with the same name as your outer function, which is causing the conflict.

To resolve this, simply rename the variable inside executeApiCalls. Here’s a quick fix:

const executeApiCalls = async () => {
  const locationData = await fetchLocationData(LOCATION_ENDPOINT, API_HOST);
  console.log(locationData);
};

This change should eliminate the ‘Cannot access before initialization’ error. Remember, it’s crucial to use unique names for variables and functions to avoid such conflicts, especially in asynchronous JavaScript. If you’re still encountering issues after this modification, double-check your API key and endpoint URL for any typos.

I’ve encountered a similar issue before, and I think I see what’s going on here. The problem lies in your executeApiCalls function. You’re using the same name ‘fetchLocationData’ for both the outer function and the variable inside executeApiCalls. This is causing a naming conflict.

To fix this, you should change the variable name inside executeApiCalls. Here’s how you could modify that part:

const executeApiCalls = async () => {
  const locationData = await fetchLocationData(LOCATION_ENDPOINT, API_HOST);
  console.log(locationData);
};

This should resolve the ‘Cannot access before initialization’ error. The outer fetchLocationData function will now be properly recognized and called. Always be careful with variable naming to avoid such conflicts, especially when working with asynchronous code. Let me know if this solves your problem!