Published:

React + Axios - 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 the axios HTTP client which is available on npm.

Other HTTP examples available:


Installing axios from npm

With the npm CLI: npm install axios

With the yarn CLI: yarn add axios


Simple GET request using axios

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 axios
    axios.get('https://api.npms.io/v2/search?q=react')
        .then(response => this.setState({ totalReactPackages: response.data.total }));
}

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


GET request using axios with React hooks

This sends the same GET request from React using axios, 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 axios inside useEffect React hook
    axios.get('https://api.npms.io/v2/search?q=react')
        .then(response => setTotalReactPackages(response.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-axios?file=App/GetRequestHooks.jsx


GET request using axios with async/await

This sends the same GET request from React using axios, 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 axios with async/await
    const response = await axios.get('https://api.npms.io/v2/search?q=react');
    this.setState({ totalReactPackages: response.data.total })
}

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


GET request using axios with error handling

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

componentDidMount() {
    // GET request using axios with error handling
    axios.get('https://api.npms.io/v2/invalid-url')
        .then(response => this.setState({ totalReactPackages: response.data.total }))
        .catch(error => {
            this.setState({ errorMessage: error.message });
            console.error('There was an error!', error);
        });
}

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


GET request using axios with set HTTP headers

This sends the same GET request again from React using axios with a couple of headers set, the HTTP Authorization header and a custom header My-Custom-Header.

componentDidMount() {
    // GET request using axios with set headers
    const headers = {
        'Authorization': 'Bearer my-token',
        'My-Custom-Header': 'foobar'
    };
    axios.get('https://api.npms.io/v2/search?q=react', { headers })
        .then(response => this.setState({ totalReactPackages: response.data.total }));
}

Example React component at https://stackblitz.com/edit/react-http-get-request-examples-axios?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