How do I send AJAX requests?

You can use any AJAX library you like in React, such as the popular Axios, jQuery AJAX and the browser’s built-in window.fetch.

At what point in the component’s life cycle should I send AJAX requests?

You should send AJAX request data within the componentDidMount lifecycle method. This way you can use setState to update your component when the requested data arrives.

Example: Use the result of an AJAX request to set state within a component

The component below shows how to use the AJAX request within the componentDidMount method and populate the state with the result within the component.

The sample API returns a JSON object with the following structure:


      
{
  items: [
    { id: 1, name: 'Apples', price: '$2' },
    { id: 2, name: 'Peaches', price: '$5' }
  ]
}

      Copy the code

      
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            <li key={item.name}>
              {item.name} {item.price}
            </li>
          ))}
        </ul>
      );
    }
  }
}


      Copy the code

Cancel the AJAX request

Note that if the component is unloaded before the AJAX request completes, you will see a warning in the browser’s control panel: Cannot read property ‘setState’ of undefined. If this is a problem for you, you can track outstanding AJAX requests and cancel them in the componentWillUnmount lifecycle method.

Error correction