vue.jsaxiosnuxt.jslaravel-apiasyncdata

Can't get data from api with axios in Nuxt components


<template>
  <div id="post">
    <p>{{ data }}</p>
  </div>
</template>

<script>
export default {
  data () {
    return {
      data: ''
    }
  },
  async asyncData({$axios}) {
    const res = await $axios.get('/v1/posts')
    .catch( error => {
      console.log("response error", error)
      return false
    })
    return {
      data: res
    }
  },
}
</script>

At first, I tried to get the data with the above code, it worked in pages/post.vue but not in components/post.vue. Then, I realized that I can't use asyncData in the nuxt components and changed the code as follows.

<template>
  <div id="post">
    <p>{{ data }}</p>
  </div>
</template>

<script>
export default {
  data () {
    return {
      data: ''
    }
  },
  mounted () {
    this.asyncData()
  },
  asyncData() {
    await axios.get('/v1/posts')
    .then(res => {
      this.data = res.data
    })
  },
}
</script>

Then, I got a syntax error "Unexpected reserved word 'await'". How can I get data via api in Nuxt components?

===================================

I read https://nuxtjs.org/docs/features/data-fetching#accessing-the-fetch-state and changed the code as below.

<script>
export default {
  data () {
    return {
      data: ''
    }
  },
  async fetch() {
    this.data = await fetch('/v1/posts')
    .then(res => res.json())
  },
}
</script>

And now, I'm stacking with another error 'Error in fetch(): SyntaxError: Unexpected token < in JSON at position 0'.


Solution

  • This code worked.

    <script>
    export default {
      data () {
        return {
          data: '',
        }
      },
      async fetch() {
        const res = await this.$axios.get('/v1/posts')
        this.data = res.data
      },
    }
    </script>