1

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.

3 Answers 3

2

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>
)
Sign up to request clarification or add additional context in comments.

Comments

1

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>
)

Comments

1

Try this componentWillUnmount() { this.props.countries = [] }, That might help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.