Reputation: 516
I want to display a message "no data available " if there will be no data after fetching from API in react js I don't know how to do you can look my code and guide me
{this.state.movies1.map(c => (
<tbody key={c.pk}>
<tr>
<th scope="row">{c.pk}</th>
<td>
<a
href="/overview/4343"
style={{ color: "#13B760" }}
class="font-weight-bold"
>
{c.user}
</a>
</td>
<td>{c.total_milage ? `${c.total_milage}` : 0} </td>
<td>{c.total_movingtime ? `${c.total_movingtime}` : 0} </td>
<td>
{c.total_averagespeed ? `${c.total_averagespeed}` : 0}
</td>
<td>{c.total_letter ? `${c.total_letter}` : 0} </td>
<td>
{c.total_ship_weight ? `${c.total_ship_weight}` : 0}
</td>
<td>{c.total_pack ? `${c.total_pack}` : 0}</td>
<td>{c.total_kg ? `${c.total_kg}` : 0} </td>
<td>{c.total_co2_save ? `${c.total_co2_save}` : 0} </td>
<td>{c.total_boxes ? `${c.total_boxes}` : 0}</td>
<td>{c.total_user ? `${c.total_user}` : 0}</td>
</tr>
</tbody>
))}
If the data will be not available in this table it should display a message that "no data available " so help me thanks
Upvotes: 2
Views: 8812
Reputation: 452
Assuming you expect empty array, you could use conditional rendering. If that's the case, you could add a check like this:
{!this.state.movies1 ? <div>no data</div> : ... // the rest of your code goes here in case there is data found.
This takes care of empty array and other falsy values, but you should be careful about handling the API response first as you might get an error message and not empty array/null/undefined value.
Upvotes: 0
Reputation: 168
Simply check your object length or null/undefined before map with help of conditional operator.
{this.state.movies1.length > 0 ? this.state.movies1.map(c => (
<tbody key={c.pk}>
<tr>
<th scope="row">{c.pk}</th>
<td>
<a
href="/overview/4343"
style={{ color: "#13B760" }}
class="font-weight-bold"
>
{c.user}
</a>
</td>
<td>{c.total_milage ? `${c.total_milage}` : 0} </td>
<td>{c.total_movingtime ? `${c.total_movingtime}` : 0} </td>
<td>
{c.total_averagespeed ? `${c.total_averagespeed}` : 0}
</td>
<td>{c.total_letter ? `${c.total_letter}` : 0} </td>
<td>
{c.total_ship_weight ? `${c.total_ship_weight}` : 0}
</td>
<td>{c.total_pack ? `${c.total_pack}` : 0}</td>
<td>{c.total_kg ? `${c.total_kg}` : 0} </td>
<td>{c.total_co2_save ? `${c.total_co2_save}` : 0} </td>
<td>{c.total_boxes ? `${c.total_boxes}` : 0}</td>
<td>{c.total_user ? `${c.total_user}` : 0}</td>
</tr>
</tbody>
)): <div>No Data avaliable</div>>}
Upvotes: 3
Reputation: 2135
You can add conditional rendering on the jsx itself. calculate the length of this.state.movies. based on that you can either show the table or a msg.
https://reactjs.org/docs/conditional-rendering.html Or
{this.state.movies.length>0 ? 'Your table code' : 'Data is not available'}
Upvotes: 0