Vue 3: Cannot read property 'id' of null

Viewed 1574

I want to show list product from api but it shows the error:

Uncaught (in promise) TypeError: Cannot read property 'id' of null
at eval (Home.vue?bb51:103)
at renderList (runtime-core.esm-bundler.js?5c40:6635)
at Proxy.render (Home.vue?bb51:2)
at renderComponentRoot (runtime-core.esm-bundler.js?5c40:1166)
at componentEffect (runtime-core.esm-bundler.js?5c40:5265)......

my product like :

[
  {
    "id": 1,
    "name": "chair",
    "categoryId": 12,
    "unitId": 2,
    "price": 66000000,
    "salePrice": 0,
    "material": "wood",
    "size": "x"
  },
]

My code here:

Home.vue file

 <ProductCard v-for="product in products" :key="product.id" :product="product" />

ProductCard.vue file

<script>
export default {
  name: "ProductCard",
  props: {
    product: {
      type: Object,
      required: true,
    },
  },
};
</script>

ProductService.js file

const apiClient = axios.create({        
    baseURL: 'http://localhost:8888/api/v1',
    withCredentials: false,
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
})

export default {
    getProducts() { 
        return apiClient.get('/product/get-list-product-by-subcategory')     
    },
}

When I print out list product in console. It still work.

Does anyone know where is the bug in my code?

Updated:

I try to fix my bug "Cannot read property 'id' of null", Steve's answer although remove my red warning in devtool but not deal my data: my data still not showing up. And I find out my code work by using this.products = response.data.data

ProductService.getProducts()
      .then((response) => (this.products = response.data.data))
      .catch((error) => console.log("error: " + error));

Explain by myself is: When console.log(this.products = response) enter image description here

And I need to use this.products = response.data.data to enter to array

enter image description here

2 Answers

Try this

<ProductCard v-for="product in products" :key="product._id" :product="product" />
apiClient.get(...)

returns a promise not the actual data from the API call.

You need to add a then. like so

apiClient.get(...).then(response => (this.products = response))

Then when the apiClient.get completes this.products will be populated with the data from the API.

Related