Languages
[Edit]
EN

React - Ajax GET request (class component)

0 points
Created by:
telsa
502

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.

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.

ā¤ļøšŸ’» šŸ™‚

Join