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.