this.setState executes before the API call



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

         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');
         }'GET', '',true);
         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.


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