I am using React to build a simple app that gets data back from some API. I am not sure what is the best way to handle the fields when some of them doesnt come back. For example, Let's say the JSON data comes back looking like the following
comicDetail : {
name : iron man,
age: {
comicAge: 35,
},
favouriteFood: {
fruit: {
apple
}
}
hobby: {
favourite: {
build machines
}
}
series: [iron man 1, iron man 2]
relationship: {
jane: iron man 1,
Mary: iron man 2
},
collection : {
image : www.image1.com
}
}
}
My React code that renders the data
renderComicDetail() {
var cd = this.props.comicDetail;
if (!cd) {
return (
<div>No Data</div>
)
}
const imageUrl = cd.collection.image
return (
<div>
<div>age: {cd.age.comicAge}</div>
<div>favourite fruit: {cd.favouriteFood.fruit}</div>
<div>favourite hobby: {cd.hobby.favourite}</div>
</div>
)
}
This code will break if either of the of cd.favouriteFood, cd.age, cd.hobby is undefined as I will be reading from undefined. (This will happen as not all fields will come back) What is the cleanest way to allow me to read the data and take care of the undefined case so I dont read .fruit from undefined.
A way I can think of is to have check cases for each part of the json data for every item. But it seems messy and will not be scalable as I might have data that looks like
You can specify a condition to render a component in JSX, your code would look something like this (assuming that if hobby or food are defined then it would have renderable properties):
var cd = this.props.comicDetail;
if (!cd) {
return (
<div>No Data</div>
)
}
const imageUrl = cd.collection.image;
return (
<div>
<div>age: {cd.age.comicAge}</div>
{cd.favouriteFood && <div>favourite fruit: {cd.favouriteFood.fruit}</div>}
{cd.hobby && <div>favourite hobby: {cd.hobby.favourite}</div>}
</div>
)
I also advice you to either create separate componet for both hobby and food, so it can make your code more readable and reusable. But it definitely depends on your specific usage.
if you only don't want to display content which is undefined, you can do like this:
return (
<div>
{cd.age && cd.age.comicAge ? <div>age:{cd.age.comicAge}</div> : <div>No data</div>
}
{cd.favouriteFood && cd.favouriteFood.fruit ? <div>favourite fruit: {cd.favouriteFood.fruit}</div> : <div>No data</div>
}
{cd.hobby && cd.hobby.favourite ? <div>favourite hobby: {cd.hobby.favourite}</div> : <div>No data</div>
}
</div>
)
or if you don't want like this, create a separate function that checks valid fields
if (!isValid(cd)) {
return (
<div>No Data</div>
)
}
isValid(obj){
// check if all objects available are valid or not and return true or false as needed.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With