[Vuejs]-How do i properly assign the products variable to the array from the response from my api

0👍

You are logging outside of the component (when the component is parsed). You probably want to console inside the loadProducts function, after you’ve awaited response.

Another problem is productData is not reactive.
You probably want to use: this.productData = response.data.products.
You don’t need the external productData (at least in what you’ve shown so far).

Here’s how I’d write your component using Options API:

<template>
  <DataTable :value="products" responsiveLayout="scroll">
    <Column v-for="col in columns" :key="col.field" v-bind="col" />
  </DataTable>
</template>

<script>
import axios from 'axios';

export default {
  data: () => ({
    products: [],
    columns: [
     { field: 'SKU', header: 'Code' },
     { field: 'name', header: 'Name' },
     { field: 'brand', header: 'Brand' },
     { field: 'color', header: 'Color' }
    ]
  }),
  mounted() {
    axios.get("http://localhost:1337/products")
      .then(({ data }) => this.products = data?.products || [])
  }
}
</script>

0👍

I don’t quite see why you’re using loadProducts, since it could also be solved using the .then keyword as such (which IMO is a lot neater to look at and also does it asynchronously):

axios.get("http://localhost:1337/products").then(res=>{
   this.productData = res.data.products;
})

Also if possible, don’t use null but [] instead when declaring data properties in vue/nuxt.

Cheers!

-1👍

it should be

productData.push(...response.data.products)

Leave a comment