1

I have the following function in my project that I access from several files.

getCountry: async function () {
  let country = null
  try {
    axios
    .get('http://ip-api.com/json/')
    .then(response => (this.country = response.data.countryCode))
    console.log('Country', country)
  } catch (error) {
    console.log(error)
  }
  return country
}

It works on the other files, but for some reason I cannot use it successfully in a particular file with this situation.

This is my data part:

 data() {
    return {
      model: {
        country: '',
        state: '',
        city: ''
      },
      country: null
    }
  },

And on mount part I am trying to do the following:

this.country = await this.getCountry()
if (this.country != null) {
  this.model.country = this.country
}

The value never gets assigned to model.country. When I check this.country value, it gets the result from the function. I suppose it might have something to do with the fact that it's an async function, but I am not sure what to do.

3
  • In your browser's network check if its calling the api or not and share complete info Commented Jul 10, 2020 at 6:19
  • It does call with success status~ Commented Jul 10, 2020 at 6:25
  • I think that the function doesn't have time to complete before it gets assigned to model.country. Commented Jul 10, 2020 at 6:31

1 Answer 1

1

await should be used inside an async function, not outside it. Please try

getCountry: async function () {
  let country;
  try {
    const response = await axios.get('http://ip-api.com/json/');
    country = response.data.countryCode;
  } catch (error) {
    console.log(error)
  }
  return country
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.