Sasha Zoria
Sasha Zoria

Reputation: 771

Nuxt. Property or method "posts" is not defined on the instance but referenced during render

I am using Nuxt js for this project. Here i am using the function asyncData to fetch data on the server side. That's, why i cant, set data to the "data" because all data is fetched on the server. But i have an error in the console "Property or method "posts" is not defined on the instance but referenced during render...".

<template>
    <div>
        <v-list v-for="item in posts">
            <v-list-tile :key="item.id">
                <v-list-tile-content>
                    <h1>{{item.title}}</h1>
                </v-list-tile-content>
            </v-list-tile>
        </v-list>
    </div>
</template>

export default {
        asyncData() {
return axios.get('https://jsonplaceholder.typicode.com/posts')
                .then(response => {
                    return {posts: response.data}
                })
        }
    }

Due to the docs, https://nuxtjs.org/guide/async-data i have only to use "posts"

Upvotes: 2

Views: 2560

Answers (2)

Bitpunk
Bitpunk

Reputation: 198

The asyncData() method is only working in pages.

From the officall nuxt.js docs:

Updated: Async data in components

  1. Use the new fetch hook that is available in Nuxt 2.12 and later versions.
  2. Make the API call in the mounted hook and set data properties when loaded. Downside: Won't work for server side rendering.
  3. Make the API call in the asyncData method of the page component and pass the data as props to the sub components. Server rendering will work fine. Downside: the asyncData of the page might be less readable because it's loading the data for other components.

Upvotes: 4

snrlx
snrlx

Reputation: 5107

As already mentioned the asyncData hook is not available in components but only for pages.

In Nuxt JS 2.12 though a new fetch hook was introduced, which navigates around the issue: https://nuxtjs.org/docs/2.x/features/data-fetching#async-data-in-components

<script>
  export default {
    data() {
      return {
        posts: []
      }
    },
    async fetch() {
      this.posts = await axios.get('https://jsonplaceholder.typicode.com/posts').then(response =>
        response.data
      )
    }
  }
</script>

Upvotes: 2

Related Questions