0

I try to load data from Json to vue component using this tutorial:
https://nuxtjs.org/guide/async-data/

This is my code:

<li class="item" v-for="post in posts"  v-bind:key="post.id">
  <nuxt-link :to="....">
   {{post.id}}. {{post.title}}
  </nuxt-link>
</li>

import axios from "axios";
export default {
    async data () {
      let { data } = await axios.get(`http://jsonplaceholder/`)
      return { posts: data } // Console: property post is not defined
    }
  }

Tell me please, what's wrong?

1
  • 2
    It should be async asyncData instead of async data. Commented Aug 5, 2018 at 11:39

5 Answers 5

3

You can do this based on Nuxt asyncData and the context guide, i.e.:

export default {
  async asyncData(context) {
    let response = await context.app.$axios.$get(`http://jsonplaceholder/`)
    return { posts: response } 
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Explaining more sid heart's reply: Function name is "asyncData" not async data. You are using async await you can use like this:

import axios from "axios";
export default {
  // Also define data function and define posts property
  data() {
    return {
      posts: {}
    }
  },

  async asyncData () {
    let { data } = await axios.get(`http://jsonplaceholder/`)
    return { posts: data } // Console: property post is not defined
   }
}

Comments

0

According to Nuxt.Js documentation, async asyncData should be written instead of async data and there is no need to import axios and you should get it from the asyncData input parameters.

<li class="item" v-for="post in posts"  v-bind:key="post.id">
  <nuxt-link :to="....">
   {{post.id}}. {{post.title}}
  </nuxt-link>
</li>

export default {
  async asyncData ({ $axios }) {
    const data = await $axios.$get('http://jsonplaceholder/')
    return { posts: data } // Console: property post is not defined
  },
}

Comments

-1

according to nuxtjs document

  async asyncData ({ params }) {
    let { data } = await axios.get(`https://my-api/posts/${params.id}`)
    return { title: data.title }
  }

in your case this should be

async asyncData () {
    let { data } = await axios.get(`http://jsonplaceholder/`)
    return { posts: data } // Console: property post is not defined
}

Comments

-2

You can use like below ( as per Nuxt and Context docs.)

export default {
   async asyncData({params, app}) {
    const { data } = await app.$axios.get(`https://www.yoursite.com/user/${params.id}/`)
    return { posts: data } 
  }
}

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.