Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render is called twice when fetching data from a REST API

Tags:

I am trying to interact with a REST API using React, and I have realized that when I fetch the data, render is called once without the data, and then again with the data.

This throws an exception when I try to process this data, but I can use an if statement to check if data is null or not. However, I am not sure if that's needed.

class App extends Component {
  state = {
    TodoList: {},
  };

  componentWillMount() {
    axios.get("http://localhost:5001/1").then((response) => {
      this.setState({
        TodoList: response.data,
      });
    });
  }

  render() {
    console.log(this.state);
    return <h1>hello </h1>;
  }
}

This is what I see in in the console: enter image description here

like image 790
Gaurang Shah Avatar asked Jan 27 '19 03:01

Gaurang Shah


1 Answers

That's perfectly normal.

Your App component flow as below:

  1. Execute render method to load the component
  2. execute codes in componentDidMount
  3. Calling axios.get which is async operation
  4. Receive data from step 2, update component state by using this.setState
  5. App component detected there's an update on state, hence execute render method to load component again

Hence, you should definitely handle the case where this.state.TodoList has no data, which happened at first load

UPDATES:

component lifecycle componentWillMount is now deprecated which means you shouldn't be using it anymore. Replace it with componentDidMount instead. Functionally wise they should be no difference in your example

like image 87
Isaac Avatar answered Oct 13 '22 20:10

Isaac