I'm trying to get the grand child value from local json file. It will work perfectly all other pages. But I couldn't get the value while using useEffect. I can get child object value. But I'm not able to get the grand child value.
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom';
const ProductDetails = (props) => {
const [Product, SetProduct] = useState({});
const { ProductId } = useParams();
const GetProduct = props.ProductData.products;
useEffect(() => {
const GetItem = (item) => {
item.forEach(element => {
if (element.id === ProductId) {
SetProduct(element)
}
});
}
GetItem(GetProduct)
}, [GetProduct, ProductId])
console.log(Product.img.thumbnail)
This is my JSON structure
"products": [
{
"id": "",
"code": "",
"name": "",
"img": {
"homeSlider": "",
"thumbnail": "",
"cover": [
{
"front": "",
"back": "",
"side": ""
}
]
}
},
{
"id": "",
"code": "",
"name": "",
"img": {
"homeSlider": "",
"thumbnail": "",
"cover": [
{
"front": "",
"back": "",
"side": ""
}
]
}
}
]
Please help me for this situation. Thanks.
CodePudding user response:
The initial state is an empty object:
const [Product, SetProduct] = useState({});
An empty object has no img
property, so this will throw the exact error you're seeing:
console.log(Product.img.thumbnail)
Either add a property to the initial object:
const [Product, SetProduct] = useState({ img: {} });
Or don't try to use that property unless it exists:
if (Product.img) {
console.log(Product.img.thumbnail)
}
CodePudding user response:
this is not about capturing the grand child. you get this error because your condition does not meet and though you have an empty object.so you don't have and "img" property on an empty object.