Published: January 27 2020
Last updated: May 12 2020

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.

Other HTTP examples available:


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 React hooks

This sends the same GET request from React using fetch, but this version uses React hooks from a function component instead of lifecycle methods from a traditional React class component. The useEffect React hook replaces the componentDidMount lifecycle method to make the HTTP GET request when the component loads.

The second parameter to the useEffect React hook is an array of dependencies that determines when the hook is run, passing an empty array causes the hook to only be run once when the component first loads, like the componentDidMount lifecyle method in a class component. For more info on React hooks see https://reactjs.org/docs/hooks-intro.html.

useEffect(() => {
    // GET request using fetch inside useEffect React hook
    fetch('https://api.npms.io/v2/search?q=react')
        .then(response => response.json())
        .then(data => setTotalReactPackages(data.total));

// empty dependency array means this effect will only run once (like componentDidMount in classes)
}, []);

Example React hooks component at https://stackblitz.com/edit/react-http-get-request-examples-fetch?file=App/GetRequestHooks.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.toString() });
            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

 


Need Some React Help?

Search fiverr for freelance React developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by