I have a map function that is iterating through an array and populating a table like this:
var programData = this.state.data.map(program => (
<tr >
<td >
{program.scheduledStartDateTime}
</td>
<td>
{program.searchableTitles[1].value.en}
</td>
</tr>
));
However, sometimes the second field: program.searchableTitles[1].value.en
is empty thus resulting in the error: TypeError: Cannot read property 'value' of undefined
How can I handle this exception? I've tried adding Try and Catch but I can't seem to find a way to make it work within JSX code.
I don't mind what goes into the field where there is no data present, it can be left empty.
Try this way
var programData = this.state.data.map(program => (
<tr>
<td>
{program.scheduledStartDateTime}
</td>
<td>
{program.searchableTitles && program.searchableTitles[1] && program.searchableTitles[1].value.en}
</td>
</tr>
));
If you are getting the data through an API call then the data might not be immediately available or if you the state is not set immediately.
You can display different view instead
var programData = this.state.data.map(program => (
<tr >
<td >
{program.scheduledStartDateTime}
</td>
<td>
{program.searchableTitles[1] ?
program.searchableTitles[1].value.en : <p> Not available </p> }
</td>
</tr>
));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.