React AJAX

In React applications, AJAX requests can be implemented using the fetch API or third-party libraries such as axios, jQuery, and others for network requests.

The following is a basic explanation of using these two methods:

Using fetch API for AJAX requests

fetchis a built-in API in the browser for making network requests. The following is usingfetchBasic steps to make an AJAX request in a React component:

  • Import fetch- If you are using a modern browser, you usually don't need to import it.fetch. However, if you need to support older browsers, you can useunfetchsuch a polyfill.

  • Using the useEffect hook- UseuseEffecthook to handle side effects, such as making network requests.

  • Make a request- Usefetchto make GET or POST requests.

  • Handle the response- Use.then()to handle the response data.

  • Error handling- Use.catch()to catch and handle errors.

  • Update state- UseuseStatehook to store the requested data and update state after the request succeeds.

Example

import React, { useState, useEffect } from 'react';

const MyComponent = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const result = await response.json();
        setData(result);
        setLoading(false);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Data from API:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default MyComponent;

Explanation:

  • useState and useEffect: UseuseStateto store the data returned by the AJAX requestdata) and loading stateloading), and useuseEffectto execute the AJAX request after the component has loaded.

  • fetch: Usefetchto make a GET request, and useresponse.json()to parse the returned JSON data into JavaScript objects.

  • Asynchronous handling: Useasync/awaitto handle asynchronous operations, ensuring the state is updated after the request completes.

  • Error handling: Infetchrequest, usetry/catchto catch and handle errors that may occur.

Using axios

axios is a Promise-based HTTP client for browsers and Node.js.

The following are the basic steps to use axios:

  1. Install axios- Install axios via npm or yarn.

    npm install axios
    
  2. Import axios- Import axios in the component.

  3. Make a request- Use axios to make GET or POST requests.

  4. Handle responses and errors- Use.then()and.catch()to handle responses and catch errors.

  5. Update state- Similar to usingfetchsimilarly, useuseStateto update state.

Example

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const MyComponent = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://api.example.com/data');
        setData(response.data);
        setLoading(false);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Data from API:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default MyComponent;

Using jQuery Online Test

The following example demonstrates fetching the latest gist share description of a GitHub user:

Data in React components can be fetched via Ajax in the componentDidMount method. When data is retrieved from the server, it can be stored in state, and then the UI can be re-rendered using the this.setState method.

When loading data asynchronously, use componentWillUnmount to cancel unfinished requests before the component unmounts.

React Example

class UserGist extends React.Component { constructor(props) { super(props); this.state = {username: '', lastGistUrl: ''}; } componentDidMount() { this.serverRequest = $.get(this.props.source, function (result) { var lastGist = result[0]; this.setState({ username: lastGist.owner.login, lastGistUrl: lastGist.html_url }); }.bind(this)); } componentWillUnmount() { this.serverRequest.abort(); } render() { return ( <div> {this.state.username}The user's latestGistshared address:a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a> </div> ); } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <UserGist source="https://api.github.com/users/octocat/gists" /> );

Try it »

The above code uses jQuery to complete the Ajax request.

Other Extensions