Nighthawk2730
Nighthawk2730

Reputation: 173

How can I update the state from an API call?

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?)
 }

Upvotes: 1

Views: 1045

Answers (1)

Sandeep Patel
Sandeep Patel

Reputation: 5148

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

Upvotes: 2

Related Questions