this.setState executes before the API call

Hello,

I am trying to update react state after API call. Here is how code looks like:

componentDidMount(){
         var myRequest = new XMLHttpRequest();
         var recentUsers;
         myRequest.onreadystatechange = function ()  {
          if (myRequest.readyState === 4 && this.status == 200) {
              document.getElementById('content').innerHTML = myRequest.response;
              recentUsers = JSON.parse(myRequest.responseText);
              console.log('loaded data');
          }
         }
         myRequest.open('GET', 'https://fcctop100.herokuapp.com/api/fccusers/top/recent',true);
         myRequest.send();
         this.setState({recentUsers: recentUsers});
         console.log('now it is time to update state');
        }

I see that ‘now it’s time to update state’ message comes before ‘loaded data’. That is why my this.state.recentUsers always return undefined. How can I update state only after the API call?

Thank you very much for any help!

You’ll want your state update to happen in your onreadystatechange callback. Even better, use the fetch API and call this.setState in the promise callback.

1 Like

Thank you, very much! It worked :slight_smile: And fetch API is indeed better

1 Like