Joshua Hansen
Joshua Hansen

Reputation: 405

[Vue warn]: Error in render: "TypeError: Cannot read property 'products' of undefined"

I got this error in console tab.

[Vue warn]: Error in render: "TypeError: Cannot read property 'products' of undefined"

My code works normally but I don't know why that error shows up. I think it because the DOM has rendered first then my data was populated after that. Is that true? If yes, how can I fix it?

Here is my component:

<template>
    <main role="main">

        <!--        <breadcrumbs></breadcrumbs>-->

        <slider></slider>
        <bestseller :products="serverData.bestsellerProducts.products"></bestseller>
        <categorized-products></categorized-products>
        <latest :products="serverData.latestProducts.products"></latest>

    </main>
</template>

<script>
    import Slider from './Slider';
    import Bestseller from './Product/Bestseller';
    import Latest from './Product/Latest';
    import CategorizedProducts from './ProductCategory/CategorizedProducts';
    import {mapGetters} from 'vuex';

    export default {
        computed: {
            ...mapGetters({
                serverData: 'getServerData'
            })
        },
        components: {
            Slider,
            Bestseller,
            Latest,
            CategorizedProducts
        }
    }
</script>

<style scoped>

</style>

Upvotes: 1

Views: 4154

Answers (3)

Nguyen Kien
Nguyen Kien

Reputation: 304

This often happens when your component renders before serverData is available. You should init this variable first in your state. Something like:

state: {
    serverData: {
        bestsellerProducts: {products: []},
        latestProducts: {products: []},
    }
}

I'd recommend separating bestSellerProducts and latestProducts from serverData.

Also make sure you handle props properly inside components. See Vue Document on Props Validation.

Upvotes: 1

Julian Sanchez
Julian Sanchez

Reputation: 101

This method is kind of ghetto but:

You could make an error handler then if the error contains that text return the function otherwise console.error() it.

Upvotes: 0

Julian Sanchez
Julian Sanchez

Reputation: 101

It looks like either bestsellerProducts or latestProducts doesn't have a products attribute. If you could post the value for these two items I'd be able to give you a better answer.

Are you pushing to the array after the render?

Upvotes: 0

Related Questions