2

I have installed axios inside my nuxt.js application. Here my configuration file code:

File: nuxt.config.js

modules: [
  '@nuxtjs/vuetify',
  '@nuxtjs/axios',
],

axios: {
  // proxyHeaders: false
}

Here my example working code:

export default {
  data() {
    return {
      ip: ''
    }
  },
  async asyncData({ $axios }) {
    const ip = await $axios.$get('http://icanhazip.com')
    return { ip }
  }
}

And here my not working code:

export default {
  data() {
    return {
      ip: ''
    }
  },
  methods: {
    async asyncData() {
      const ip = await this.$axios.$get('http://icanhazip.com')
      this.ip = ip
    }
  } 
}

Why inside methods axios request not working?

1
  • When are you calling the method? Commented Jun 19, 2019 at 13:45

2 Answers 2

1

You cannot call asyncData in you methods object. asyncData is for pre rendering only.

Rename your function to something else and it should be fine:

export default {
  data() {
    return {
      ip: ''
    }
  },
  methods: {
    async getData() {
      const ip = await this.$axios.$get('http://icanhazip.com')
      this.ip = ip
    }
  } 
}

Also when you are using asyncData as in your top example, you should not initialise "ip" in your data function. What is returned from asyncData is merged into data anyway.

Sign up to request clarification or add additional context in comments.

Comments

0

AsyncData method will be called everytime before loading the page also note that asyncdata is only available in page component in nuxt. You don't have access to the component instance through this inside asyncData because it is called before initiating the component. You can use the returned data from asyncData data in your template without initialising in your data.

Nuxt asyncData

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.