Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - load the data before rendering the component

Tags:

reactjs

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?

like image 287
Adel Avatar asked Oct 20 '17 14:10

Adel


2 Answers

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: {...}
    };
}
like image 149
Tim B James Avatar answered Oct 12 '22 08:10

Tim B James


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.

like image 3
palsrealm Avatar answered Oct 12 '22 08:10

palsrealm