I am trying to implement asynchronous XMLHttpRequest in react. Here is my attempt:
It is recommended to make AJAX calls in the componentDidMount
lifecycle method.
componentDidMount
is for side effects. Adding event listeners, AJAX, mutating the DOM, etc.
Also, you should consider using the new fetch API.
class Welcome extends React.Component {
constructor() {
this.state = {
data: null,
};
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/photos/').then(res => {
return res.json()
}).then(res => {
this.setState({ data: res});
}).catch(err);
}
render() {
if (this.state.data) {
return
}
else {
return Loading...
}
}
}