I create weather app and made some component which has fields in data section, then in methods section I changed value of fields and try to get it in other method but I get old value(value was not changed)
<template>
<div id = "container">
</div>
</template>
<script>
export default {
name: 'App',
components: {
},
data () {
return {
city: '',
region: '',
country: '',
// Geographical coordinates (latitude, longitude)
lat: 0,
lon: 0
}
},
methods: {
async getGeolocationInformation () {
const API_KEY = 'c3ee06c52efd44b08f2eeade4bc574d9'
const API_URL = 'https://ipgeolocation.abstractapi.com/v1/?api_key=' + API_KEY
const apiResponse = await fetch(API_URL)
const data = await apiResponse.json()
const { city, country, region } = data
this.$data.city = city
this.region = region
this.country = country
this.lon = 100
},
getCoordinatesCityByName () {
alert(this.lon)
},
setCity (city){
this.city = city
},
},
created () {
this.getGeolocationInformation()
this.getCoordinatesCityByName()
},
}
</script>
I tried to read some articles,but the same code worked there,but not for me
2
Answers
In your code, you are calling the getCoordinatesCityByName() method immediately after calling the getGeolocationInformation() method in the created() lifecycle hook. However, the getGeolocationInformation() method is asynchronous, meaning it takes some time to fetch the data from the API and update the values.
When you call getCoordinatesCityByName(), it is executed before the asynchronous operation of getGeolocationInformation() completes, so you are trying to access the lon property before it has been updated with the new value.
To ensure that you access the updated value, you need to wait for the asynchronous operation to complete before calling getCoordinatesCityByName(). One way to achieve this is by using async/await syntax within the created() hook.
Keep in mind not to store API keys in your code 😉
Here’s an updated version of your code:
getGeolocationInformation
function isasynchronous
, and thegetCoordinatesCityByName
function will execute before the API return the response and set the values, so you need toawait
it to only execute thegetCoordinatesCityByName
function aftergetGeolocationInformation
.