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