Published:

React + Fetch - HTTP GET Request Examples

Below is a quick set of examples to show how to send HTTP GET requests from React to a backend API using fetch() which comes bundled with all modern browsers.

Simple GET request using fetch

This sends an HTTP GET request from React to the npm api to search for all react packages using the query q=react, then assigns the total returned in the response to the component state property totalReactPackages so it can be displayed in the render() method.

componentDidMount() {
    // Simple GET request using fetch
    fetch('https://api.npms.io/v2/search?q=react')
        .then(response => response.json())
        .then(data => this.setState({ totalReactPackages: data.total }));
}

Example React component at https://stackblitz.com/edit/react-http-get-request-examples-fetch?file=App/GetRequest.jsx


GET request using fetch with async/await

This sends the same GET request from React using fetch, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).

async componentDidMount() {
    // GET request using fetch with async/await
    const response = await fetch('https://api.npms.io/v2/search?q=react');
    const data = await response.json();
    this.setState({ totalReactPackages: data.total })
}

Example React component at https://stackblitz.com/edit/react-http-get-request-examples-fetch?file=App/GetRequestAsyncAwait.jsx


GET request using fetch with error handling

This sends a GET request from React to an invalid url on the npm api then assigns the error to the errorMessage component state property and logs the error to the console.

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response.ok property to see if the request failed and reject the promise ourselves by calling return Promise.reject(error);. This approach means that both types of failed requests - network errors and http errors - can be handled by a single catch() block.

componentDidMount() {
    // GET request using fetch with error handling
    fetch('https://api.npms.io/v2/invalid-url')
        .then(async response => {
            const data = await response.json();

            // check for error response
            if (!response.ok) {
                // get error message from body or default to response statusText
                const error = (data && data.message) || response.statusText;
                return Promise.reject(error);
            }

            this.setState({ totalReactPackages: data.total })
        })
        .catch(error => {
            this.setState({ errorMessage: error });
            console.error('There was an error!', error);
        });
}

Example React component at https://stackblitz.com/edit/react-http-get-request-examples-fetch?file=App/GetRequestErrorHandling.jsx


GET request using fetch with set HTTP headers

This sends the same GET request again from React using fetch with the HTTP Content-Type header set to application/json.

componentDidMount() {
    // GET request using fetch with set headers
    const headers = { 'Content-Type': 'application/json' }
    fetch('https://api.npms.io/v2/search?q=react', { headers })
        .then(response => response.json())
        .then(data => this.setState({ totalReactPackages: data.total }));
}

Example React component at https://stackblitz.com/edit/react-http-get-request-examples-fetch?file=App/GetRequestSetHeaders.jsx

 

Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

 


Supported by