0

I'm doing my first project using JavaScript, I want to get the user IPV4, and then use it to get the weather.

let ipv4
const ipv4Url = 'https://api.ipify.org?format=json'
fetch(ipv4Url)
.then(response => response.json())
.then(data => {
    ipv4 = data.ip
    console.log(ipv4)
})
.catch(error => {
    console.error('Error fetching data: ', error)
})
//Why is it undefined in here?
console.log(ipv4)

The first console.log returns the value I want, but the latter doesn't.

Then I would start the next step using the previous information(which doesn't work) to get the weather.

const weatherUrl = 'http://api.weatherapi.com/v1/current.json?q=' + ipv4
const weatherKey = 'f7ac7ff557154dac866131959231508'


let weatherJson
fetch(weatherUrl, {
    method: "GET",
    headers: {
        "key": weatherKey
    }
})
.then(response => response.json())
.then(data => {
    weatherJson = data
})
.catch(error => {
    console.error('Error fetching data:', error);
    });

//I have the same problem here
console.log(weatherJson)

Can someone explain why the variable becomes undefined ?

Loknitro
  • 11
  • 3
  • 1
    `fetch` calls are asynchronous, so it executes the `console.log` calls before the `fetch` has actually finished running. You probably want to look into `async`/`await`. – ceejayoz Aug 16 '23 at 17:58
  • *"The first console.log returns the value I want, but the latter doesn't."* - Pay close attention to the **order** in which these two things happen. – David Aug 16 '23 at 18:00

0 Answers0