1

I keep getting the following error when I try to run a GET request from Rapid API

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

const RAPIDAPI_KEY =
  import.meta.env.VITE_RAPIDAPI_KEY;
const GEOLOCATION_URL = "https://ip-geo-location.p.rapidapi.com/ip/check?format=json";
const GEOLOCATION_HOST = "ip-geo-location.p.rapidapi.com";

const getData = async(url, host) => {
  const response = await fetch(url, {
    method: "GET",
    headers: {
      accept: "application/json",
      "x-rapidapi-host": host,
      "x-rapidapi-key": RAPIDAPI_KEY
    }
  })

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`)
  }

  return await response.json();
}

const runApiQueries = async() => {
  // GET CITY NAME
  const getData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);
  console.log(getData);
}

runApiQueries();
Amen Ra
  • 2,843
  • 8
  • 47
  • 85
  • Try changing the variable name in runApiQueries method, maybe due to the same name, javascript compiler getting confused. – Usama Majid Mar 10 '22 at 07:03

1 Answers1

3

The problem is the line

  const getData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);

it should've been

  const data = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);

Under any circumstances, you shouldn't specify variable name the same as function or any other defined identifier.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Flynn
  • 181
  • 4