I am trying to implement asynchronous XMLHttpRequest in react. Here is my attempt:
You need to perform the ajax request within the React lifecycle. The easiest way is to listen to componentDidMount
, perform your ajax request, and then set the state.
class Welcome extends React.Component {
constructor() {
this.state = {
data: null,
};
}
componentDidMount() {
var xhr = new XMLHttpRequest();
var status = false;
xhr.open("GET", "https://jsonplaceholder.typicode.com/photos/", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
this.setState({ data: xhr.responseText });
status = true;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
render() {
if (this.state.data) {
return
}
else {
return Loading...
}
}
}
You can read more about the component lifecycle here: https://facebook.github.io/react/docs/react-component.html