My components code is like below
componentDidMount = () => {
this.props.dispatch(getCountry());
}
render() {
let rows = this.props.countries.map((item, index) => (//some code here));
return (
<div>
{rows ? (
//components HTML code here
) : (
<img src="loading.gif" alt="Loading ..."/>
)}
</div>
)
}
But the component is loading before API fetched data.
You can check for rows
data since it would be an empty array if not fetched.
return (
<div>
{rows && rows.length ? (
//components HTML code here
) : (
<img src="loading.gif" alt="Loading ..."/>
)}
</div>
)
You can also write your condition like rows && rows.length > 0
same with rows && rows.length
. Therows.length
if it's empty will resolved to 0
which is false
, but if greather than 0 will be true
(Typecasting or type conversion).
return (
<div>
{(rows && rows.length > 0 ? (
//components HTML code here
) : (
<img src="loading.gif" alt="Loading ..."/>
)}
</div>
)