Languages
[Edit]
EN

React - Ajax GET request (class component)

0 points
Created by:
telsa
472

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.

ReactJS

React - Ajax GET request (class component)
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