React - Ajax GET request

3 points
Created by:

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';
            .then(response => response.text())
            .then(responseText => {
          		if (componentRemoved) {
          		setResponse(`Response: ${responseText}`);
            .catch(error => {
          		if (componentRemoved) {
            	setResponse('Request error!');
        return () => {
          	componentRemoved = true;
    }, []);
    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 the 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

Alternative titles

  1. React - fetch method example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

React Ajax

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂