React - Ajax GET request

3 points
Created by:
Dirask Community

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 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 response value.

Runnable example:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
//import React from "react";

const App = () => {
  const [response, setResponse] = React.useState();
  React.useEffect(() => {
    const requestText = 'hello';
      .then(responseData => responseData.text())
      .then(responseText => {
        setResponse(`Response: ${responseText}`);
      .catch(error => {
        setResponse('Request error!');
  return (

const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );

Spring MVC server site GET methods example

Server side logic that may handle requests for above example can be written with Spring Framework.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

public class EchoGetController {

    @RequestMapping(value = "/examples/echo", method = RequestMethod.GET)
    public String makeGetEcho(@RequestParam("text") String text) {
        return text;

See also

  1. JavaScript Ajax GET request with Java Spring MVC controller
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé