{{ data }}

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

1.4k Views Asked by At
<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'.

2

There are 2 best solutions below

0
Takichee On BEST ANSWER

This code worked.

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

Glad that found a solution to your issue.

You can even use this.$axios.$get directly if you don't want to have to write .data afterwards.