Mac Mac -3 years ago 206
Javascript Question

Asynchronous xmlhttp request in react

I am trying to implement asynchronous XMLHttpRequest in react.
Here is my attempt:



var xhr = new XMLHttpRequest();
var json_obj, status = false;
xhr.open("GET", "https://jsonplaceholder.typicode.com/photos/", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
json_obj = xhr.responseText;
status = true;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);

class Welcome extends React.Component {
render() {
return (
<div>
<img src= {status ? json_obj[0].url : 'loading...'}></img>
</div>
);
}
}
ReactDOM.render(
<Welcome/>,
document.getElementById('root')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>





I have been thinking about adding listener to it but i don't know how to do it.

Overall i am having problem with an update after async XMLHttpRequest loads and returns value.

Answer Source

Use the component's lifecycle to load the data and then set the state asynchronously. You will also need to use JSON.parse on the data returned to you.

class Welcome extends React.Component {
  state = {}

  componentDidMount() {
    var xhr = new XMLHttpRequest();
    var json_obj, status = false;
    xhr.open("GET", "https://jsonplaceholder.typicode.com/photos/", true);
    xhr.onload = function (e) {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          var json_obj = JSON.parse(xhr.responseText);
          status = true;
          this.setState({ json_obj });
        } else {
          console.error(xhr.statusText);
        }
      }
    }.bind(this);
    xhr.onerror = function (e) {
      console.error(xhr.statusText);
    };
    xhr.send(null);
  }

  render() {
    return (
      <div>
          <img src= {this.state.json_obj ?  this.state.json_obj[0].url : 'loading...'}></img>
      </div>
    );
  }
}
ReactDOM.render(
   <Welcome/>,
   document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download