1

I make a call to my server, which is expecting an object back from this call.

constructor(props) {
super(props);
this.state ={todos: []};
}
componentDidMount() {
 console.log("HELLO");
 axios.get("http://localhost:4000/todos")
.then(response =>{
  console.log(response.data); // this works
  this.setState({todos: response.data});
  })
 console.log(this.state.todos); // this does not (why?)
 }
  • Does these answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) and [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/q/30782948/996081) – cbr Sep 17 '20 at 15:46

1 Answers1

2

this.setState({todos: response.data}) is not synchronous. console.log(this.state.todos) may be executed before setState

From react doc:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which is guaranteed to fire after the update has been applied.

If you need to set the state based on the previous state, read about the updater argument below.

this.setState({todos: response.data},function () {
     console.log(this.state.todos);
});

read this out for more detail: https://reactjs.org/docs/react-component.html#setstate

Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37
  • So I have some code that I render based on this and the state is not updated there either for some reason. That's why I tried to debug it using console.log – Nighthawk2730 Sep 18 '20 at 04:56