EN
React - Ajax GET request
3 points
In this article, we would like to show you how to make a simple AJAX request in React.
We use React.useState
hook to store the response from the server. fetch
method takes path
to the resource we want to fetch, then .text()
method converts data
received from the server to the text and with setResponse
sets the state response
value.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [response, setResponse] = React.useState();
7
React.useEffect(() => {
8
let componentRemoved = false;
9
const requestText = 'hello';
10
fetch(`/examples/echo?text=${encodeURIComponent(requestText)}`)
11
.then(response => response.text())
12
.then(responseText => {
13
if (componentRemoved) {
14
return;
15
}
16
setResponse(`Response: ${responseText}`);
17
})
18
.catch(error => {
19
if (componentRemoved) {
20
return;
21
}
22
setResponse('Request error!');
23
});
24
return () => {
25
componentRemoved = true;
26
};
27
}, []);
28
return (
29
<div>{response}</div>
30
);
31
};
32
33
const root = document.querySelector('#root');
34
ReactDOM.render(<App/>, root );
Server side logic that may handle requests for the above example can be written with Spring Framework.
xxxxxxxxxx
1
import org.springframework.stereotype.Controller;
2
import org.springframework.web.bind.annotation.*;
3
4
5
public class EchoGetController {
6
7
value = "/examples/echo", method = RequestMethod.GET) (
8
9
public String makeGetEcho( ("text") String text) {
10
return text;
11
}
12
}