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:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const [response, setResponse] = React.useState();
React.useEffect(() => {
let componentRemoved = false;
const requestText = 'hello';
fetch(`/examples/echo?text=${encodeURIComponent(requestText)}`)
.then(response => response.text())
.then(responseText => {
if (componentRemoved) {
return;
}
setResponse(`Response: ${responseText}`);
})
.catch(error => {
if (componentRemoved) {
return;
}
setResponse('Request error!');
});
return () => {
componentRemoved = true;
};
}, []);
return (
<div>{response}</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );
Spring MVC server site GET methods example
Server side logic that may handle requests for the above example can be written with Spring Framework.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class EchoGetController {
@RequestMapping(value = "/examples/echo", method = RequestMethod.GET)
@ResponseBody
public String makeGetEcho(@RequestParam("text") String text) {
return text;
}
}