EN
React - Ajax GET request (class component)
0
points
In this article, we would like to show you how to make a simple AJAX request in React.
We use the component's stateĀ to store theĀ responseĀ from the server. TheĀ fetch
Ā method takesĀ path
Ā to the resource we wantĀ to fetch, thenĀ .text()
Ā methodĀ converts responseĀ receivedĀ from the server to the textĀ and with setState()
Ā method sets the stateĀ response
Ā value.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
response: ''
};
}
render(){
const requestText = 'hello';
fetch(`/examples/echo?text=${encodeURIComponent(requestText)}`)
.then(response => response.text())
.then(responseText => {
this.setState({response: responseText});
})
.catch(error => {
this.setState({response: 'Request error!'});
});
return (
<div>{this.state.response}</div>
);
}
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Note:
Go to this article to see functional component example.