Reputation: 7028
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.
Upvotes: 1
Views: 2601
Reputation: 1250
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>
)
Upvotes: 1
Reputation: 11
Try this componentWillUnmount() {
this.props.countries = []
}
, That might help you.
Upvotes: 1
Reputation: 5402
rows
is an array hence !rows
will still be true. Try this :
return (
<div>
{rows && rows.length ? (
//components HTML code here
) : (
<img src="loading.gif" alt="Loading ..."/>
)}
</div>
)
Upvotes: 2