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:
That's perfectly normal.
Your App
component flow as below:
render
method to load the componentcomponentDidMount
axios.get
which is async operationthis.setState
App
component detected there's an update on state, hence execute render
method to load component againHence, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With