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 ?