TypeError: Cannot read property 'name' of undefined

hi I’m trying to access an array of object like this ( {product.name} ) and get this type of error in reactjs

TypeError: Cannot read property ‘name’ of undefined

here’s the code

import React from 'react';
import data from '../data';
import { Link } from 'react-router-dom';

function ProductScreen(props) {
    console.log(props.match.params.id);
    const product = data.products.find(x => x._id === props.match.params.id);
    return <div>
        <div>
            <Link to="/">Back to results</Link>
        </div>
        <h1>{product.name}</h1>
    </div>
}
export default ProductScreen;

and this is the array i’m trying to access

export default {
    products:[{
        _id: 1,
        name: '4 season Pizza',
        category: 'pizza',
        image: '/images/4.jpeg',
        price: '7000 rwf',
        brand: 'Pizza',
        rating: 4.5,
        numReviews: 10
    },
    {
        _id: 2,
        name: 'ham sandwich',
        category: 'sandwitch',
        image: '/images/3.jpeg',
        price: '1500 rwf',
        brand: 'sandwitgh',
        rating: 4.5,
        numReviews: 10
    },
    {
        _id: 3,
        name: 'beef Burger',
        category: 'burger',
        image: '/images/1.jpeg',
        price: '3500 rwf',
        brand: 'Burger',
        rating: 4.5,
        numReviews: 10
    },
    {
        _id: 4,
        name: 'chicken Burger',
        category: 'burger',
        image: '/images/2.jpeg',
        price: '4000 rwf',
        brand: 'Burger',
        rating: 4.5,
        numReviews: 10
    },
    {
        _id: 5,
        name: 'Veg Burger',
        category: 'burger',
        image: '/images/1.jpeg',
        price: '3000 rwf',
        brand: 'Burger',
        rating: 4.5,
        numReviews: 10
    }]
}

help me please I’m trying to learn reactjs

I guess you’re trying to read an object that is not found.

I guess a simple fallback should prevent your app from throwing the error:

{product ? 
[your code]  
: <p>This are not the droids you are looking for</p>
}

yes, the object is not being found! but why? and how can I solve the problem?

cause i don’t need a hard coded thing.

I have too few information about the reasoning why it’s failing. Can you create a reproducible demo?

Maybe you don’t need my hard coded p, but that was example, handle your errors as you please :slight_smile:

thanks Marmiz, it turns out I was comparing a string with number! I solved the issue with the following code by converting the string into a number like you see bellow

const product = data.products.find(x => Number(x._id) === Number(props.match.params.id));