Reputation: 329
I am setting a React App with Laravel backend as an API Provider. I am getting an two different errors for rendering two different type of objects.
My data look like this:
{
"id": 1,
"name": "Harshit Mahajan",
"father_name": "R Mahajan",
"phone_number": "1234",
"place": {
"id": 1,
"name": "Khargone"
},
"mortages": [
{
"id": 2,
"items": "item1, item2",
"amount": "20000.00",
"mortage_at": "2020-08-31 20:09:26",
"status": {
"name": "Not Cleared"
}
},
{
"id": 3,
"items": "item3, item4",
"amount": "12000.00",
"mortage_at": "2020-08-31 20:09:56",
"status": {
"name": "Not Cleared"
}
}
]
}
I am able to render the following things by writing this code:
{this.props.mortage.name} {/* Harshit Mahajan*/}
{this.props.mortage.father_name} {/* R Mahajan*/}
{this.props.mortage.phone_number} {/* 1234 */}
Case 1: But when I try to access the place name by:
{this.props.mortage.place.name}
I am getting an error:
TypeError: Cannot read property 'name' of undefined
For this code, I am getting this error:
{this.props.mortage.place}
Error: Objects are not valid as a React child (found: object with keys {id, name}). If you meant to render a collection of children, use an array instead.
Case 2: Also when I try to access the array of mortages by:
{this.props.mortage.mortages.map(m => <div>{m.item}</div> )}
TypeError: Cannot read property 'map' of undefined
What am I doing wrong?
Upvotes: 1
Views: 94
Reputation: 167212
This is a common problem with React and props
that the props
may not be populated when the components render. So the component renders multiple times actually and displays the information for us.
To see why this happens, you need to render the component (say, including it using a map()
or normal way), only when all of the required data is present.
The quick and dirty solution for this is:
{this.props.mortage && this.props.mortage.place && this.props.mortage.place.name}
Check the above values are there, then show the value. If you're using the latest version of Node JS for running it and a recent version of React, which is what I presume, use this:
{this.props?.mortage?.place?.name}
Debugging
The best way to debug this information is, personally I use this method:
<pre>{JSON.stringify(this.props, null, 2)}</pre>
This will show me what are the contents. So when it loads without the data first and later if the data gets loaded, based on that I start my debugging process.
Also, in your rendering function, if you can add:
console.log(this.props);
as the first statement, you can actually see how the props
are getting populated.
Once again, you're not alone. This is common in reactive programming languages using Virtual DOM like React and others.
Upvotes: 1