5

In the ReactJS, I am changing the route to some new one with an "id", then based on this "id", I must call an API and fetch data.

I have used the API call in componentDidMount and componentWillMount and tried setState() to have my data in the state. but they didn't work in my case.

The problem is in the render() part when I want to use my data (from state), the data is not there because the API call takes some time to update the state.

Here is my code:

  componentDidMount() {
    api.get(id).then((response) => {
     this.setState({response,});
  });

With this approach, I don't have the data when I want it (render method), it will eventually be in the state but too late!

How can I change my approach to fix the loading problem?

2 Answers 2

9

The way you are doing it, you could validate the response state object in your render method, and if it is null/empty, then return <div>Loading...</div>.

When your state is then updated based on the response, the component will automagically re-render. This time, the object will be populated and you can return your component HTML.

e.g.

render(){

    if (!this.state.response){
        return <div>Loading...</div>
    }

    return (
        <div>Proper Stuff</div>
    );
}

Edit On a site note, if you set the initial state in the constructor, you can make sure the object isn't empty, but just has null/empty values. This could also help depending what your render method is doing, e.g.

constructor(props){
    super(props);

    this.state = {
        response: {...}
    };
}
Sign up to request clarification or add additional context in comments.

Comments

3

Your render code should be

render(){
 return({this.state.response?
          <div> Render your component here</div>: 
          <div> Loading ... </div>});
}

This way your component would not render till it has the data and show Loading ... text instead.

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.