Home > database >  How to iterate on a collection (array) of objects in Nuxt?
How to iterate on a collection (array) of objects in Nuxt?

Time:06-23

I'm building a small project where it has a component in it, I should render the data from the API.

Here is my code:

<template>
  <div>
    <p v-if="$fetchState.pending">Fetching products...</p>
    <p v-else-if="$fetchState.error">An error occurred :(</p>
    <div v-else>
      <h1>Nuxt products</h1>
      <ul>
        <li
          v-for="(product, key) of product"
          :key="product.id"
          :img="product.img"
        >
          {{ product.description }}
        </li>
      </ul>
      <button @click="$fetch">Refresh</button>
    </div>
  </div>
</template>

<script>
export default {
  async fetch() {
    this.products = await this.$axios("https://dummyjson.com/products");
  },
};
</script>

and here is the error code:

Property or method "product" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option or for class-based components, by initializing the property

CodePudding user response:

This works

<template>
  <div>
    <p v-if="$fetchState.pending">Fetching products...</p>
    <p v-else-if="$fetchState.error">An error occurred :(</p>
    <div v-else>
      <h1>Nuxt products</h1>
      <ul>
        <li v-for="product in products" :key="product.id" :img="product.img">
          {{ product.description }}
        </li>
      </ul>
      <button @click="$fetch">Refresh</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      products: [],
    };
  },
  async fetch() {
    const response = await this.$axios.$get('https://dummyjson.com/products')
    this.products = response.products
  },
}
</script>

You need v-for="product in products" as explained here: enter image description here

We can see that as usual, the actual data is inside data, hence you can use the $get shortcut: https://axios.nuxtjs.org/usage#-shortcuts

Then you need to access the products field to have the data to iterate on. Using the Vue devtools network tab greatly helps debugging that one!

CodePudding user response:

so the answer is i missed putting the data as @kissu has mentioned above

<template>
  <div>
    <p v-if="$fetchState.pending">Fetching products...</p>
    <p v-else-if="$fetchState.error">An error occurred :(</p>
    <div v-else>
      <h1>Nuxt products</h1>
      <ul>
        <li v-for="product in products" :key="product.id">
          {{ product.description }}
          {{ product.images }}
        </li>
      </ul>
      <button @click="$fetch">Refresh</button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      products: [],
    };
  },
  async fetch() {
    const response = await this.$axios.$get("https://dummyjson.com/products");
    this.products = response.products;
  },
};
</script>
  • Related