I'm fairly new to React and was having difficulties displaying the data I had returned back from an Axios API call into the front-end interface of the application. Currently, I've been trying to map the data to a list of items to display this information on the front-end but for whatever reason, the data isn't being displayed at all? could someone help me figure out the best approach when it comes to mapping the array data and displaying it onto the front-end? I'll be attaching a picture of the json object and a snippet of code that works with one approach when mapping the data that returns back from the Axios API call.
Data object returned back from Axios Call
return (
<Container fluid className="content-block">
<Row style={{ paddingTop: "20px" }}>
<Col md={6}>
<h1>User Search</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text" className="form-control" {...register("userID", { required: true, minLength: 2 })}/>
{errors.userID && <p className="error-text">userID is required</p>}
<Button variant='form' type="submit">Submit</Button>
</form>
</Col>
</Row>
{!!procedureServiceList && !!procedureServiceList.specificRecommendations &&
<Row>
<Col md={6}>
<h1 style={{paddingTop:"20px"}}>Procedures List</h1>
<h2>Recommendations</h2>
<ul> {procedureServiceList.specificRecommendations.map(item => <li key={item.id}>{item.title}</li>)}</ul>
</Col>
</Row>
}
</Container>
)
as in the comment above, your method is correct and popular. I think there's no need to change anything here
{
procedureServiceList?.specificRecommendations?.length > 0 ?
<Row>
<Col md={6}>
<h1 style={{ paddingTop: "20px" }}>Procedures List</h1>
<h2>Recommendations</h2>
<ul> {procedureServiceList.specificRecommendations.map(item => <li key={item.id}>{item.title}</li>)}</ul>
</Col>
</Row> : 'No data'
}
If your data does not necessary have a unique/distinctive key, as in your case here, then it's best to introduce a separate parameter that's auto-incremented by the map() function.
Here's how your list would look like:
<ul>
{procedureServiceList.specificRecommendations.map(
(item, i) => <li key={i}>{item.title}</li>
)}
</ul>
Notice that we've introduced a parameter i which map will auto-increment as it loops over your list items. Feel free to add a console.log(i) somewhere to appreciate how it works!