I am trying to implement asynchronous XMLHttpRequest in react. Here is my attempt:
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 (
);
}
}
ReactDOM.render(
,
document.getElementById('root')
);