GET HTTP Request in React

Introduction

When developing web applications - we routinely access resources hosted on a server. Asking for, sending, or performing other operations on resources is accomplished through HTTP requests. These requests are sent from the client to a host on a server. When making HTTP request, the client employs a URL (Uniform Resource Locator) and a payload that contains the necessary information to access the server resources.

The five commonplace HTTP request methods are GET, PUT, POST, PATCH, and DELETE. These methods allow us to perform standard CRUD operations.

In this article, we will learn how to make a GET HTTP request in React using either Axios or the Fetch API, as well as how to do so in both class and functional components.

Note: In this article, we will use the JSON Placeholder Free Fake Posts REST API to perform a GET HTTP request on its server to retrieve some resources.

What is GET Request?

GET is an HTTP request method that is used to obtain resources from servers.

Axios and the Fetch API are the two main methods for making HTTP requests.

  • The Fetch API is a built-in promise-based JavaScript module for retrieving resources from a server or an API endpoint.
  • Axios is a promise-based HTTP client library that makes it simple to send asynchronous HTTP requests to REST endpoints. This is an external library that must be installed.

In this article, we'll look at how to perform GET requests in React functional components using the Fetch API and Axios methods, and then how to do the same in class-based components.

How To Perform GET HTTP Request in React's Functional Components

A functional component is created when a JavaScript function (either normal or ES6) returns a React element (JSX). We use React hooks when working with functional components, which are very important when performing GET requests.

We'll use the useState() and useEffect() hooks. Because the useEffect() hook renders immediately when the app mounts we always perform GET requests within it, and we use the useState() hook to store our data/response.

How To Perform GET HTTP Request in React's Functional Component with the Fetch API

The fetch() method accepts one mandatory argument - the URL to the resource we want to fetch, as well as an optional argument that indicates the request method. The default value for that optional argument is GET, so it is not necessary to set it when making a GET request.

Then Fetch API returns a Promise, so we can use the then() and catch() methods to handle success or failure:

import { useState, useEffect } from 'react';

const App = () => {
   const [posts, setPosts] = useState([]);

   useEffect(() => {
      fetch('https://jsonplaceholder.typicode.com/posts')
         .then((res) => res.json())
         .then((data) => {
            console.log(data);
            setPosts(data);
         })
         .catch((err) => {
            console.log(err.message);
         });
   }, []);

   return (
      // ... consume here
   );
};

This is what a standard GET request looks like. Now, let's decompose what we've done so far so that you gain a better understanding of the code above. First of all, we created a state to hold all the resources/posts we would fetch from the posts API:

const [posts, setPosts] = useState([]);

Then we made use of the useEffect() hook and wrote our GET request in it so that the request is triggered immediately after the app mounts:

useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((data) => {
         console.log(data);
         setPosts(data);
      })
      .catch((err) => {
         console.log(err.message);
      });
}, []);

After that, we created a fetch request in the useEffect() hook and passed the URL we can use to access the server. Since this returns a promise, we used the then() method. Because this method returns a response object rather than JSON, we first converted the data to JSON format:

useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
}, []);

Then we proceeded to get the posts/data and stored them in the state we created earlier:

useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((data) => {
         console.log(data);
         setPosts(data);
      }
}, []);

Finally we use the catch() method to handle errors:

useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((data) => {
         console.log(data);
         setPosts(data);
      })
      .catch((err) => {
         console.log(err.message);
      });
}, []);

We've already performed a GET request and saved our data to the state we created. Now we can consume the data within our React application.

How To Perform GET HTTP Request in React's Functional Component With Axios

Aside from the Fetch API, we can also use Axios to send GET requests. Axios is a promise-based HTTP client library that makes it simple to send asynchronous HTTP requests to REST endpoints.

If we want to use Axios, which is an external library, we must first install it in our project by running the following command in our project's directory:

$ npm install axios

Once we've successfully installed Axios, we can proceed to perform our GET request:

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

const App = () => {
   const [posts, setPosts] = useState([]);

   useEffect(() => {
      axios
         .get('https://jsonplaceholder.typicode.com/posts?_limit=10')
         .then((response) => {
            setPosts(response.data);
         })
         .catch((err) => {
            console.log(err);
         });
   }, []);

   return (
      // ...
   );
};
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This looks a lot cleaner than that of Fetch API! Taking a look at the code above, we started by importing Axios since it was an external library we installed:

import axios from 'axios';

We then performed the GET request within the useEffect() hook as we did for Fetch API, but this time the syntax is a little different:

useEffect(() => {
   axios
      .get('https://jsonplaceholder.typicode.com/posts?_limit=10')
      .then((response) => {
         setPosts(response.data);
      })
      .catch((err) => {
         console.log(err);
      });
}, []);

In contrast to the Fetch API method, no options are required to declare the method. We simply attach the method to the instance and query it, also there is no need to convert the data because it returns it as JSON.

How To Perform GET HTTP Request in React's Class Component

A class component is an ES6 class that returns JSX and requires React extensions to be used. Before the introduction of hooks, this was the most commonly used method (i.e. earlier versions 16.8) because the state could not be used within functional components.

Despite the availability of hooks, many people continue to use class components. Let's look at how we can use the constructor() method's state property, and the ComponentDidMount() lifecycle method to perform GET HTTP requests in React with class components.

How To Perform GET HTTP Request in React's Class Components With Fetch API

This is very similar to how we performed the GET request in functional components. The only difference is that we will now use the state property in the constructor() method rather than the useState() hook. Also, we will handle our GET request in the ComponentDidMount() lifecycle rather than the useEffect() hook, so that this request is triggered once our app mounts:

import React, { Component } from 'react';

class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         posts: [],
      };
   }

   componentDidMount() {
      fetch('https://jsonplaceholder.typicode.com/posts')
         .then((response) => response.json())
         .then((data) => this.setState({ posts: data }))
         .catch((error) => console.log(error));
   }

   render() {
      const { posts } = this.state;

      return (
         // ... 
      );
   }
}

In the code above, we made use of the constructor method to initialize an object's state to store the resource/data we will get from our server/API:

constructor(props) {
   super(props);
   this.state = {
      posts: [],
   };
}

We then performed our GET request in the componentDidMount() lifecycle method so that it's triggered once the app mounts:

componentDidMount() {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json())
      .then((data) => this.setState({ posts: data }))
      .catch((error) => console.log(error));
}

state is an object which holds many states, we first destructure it to get the posts state, which can later be used:

render() {
   const { posts } = this.state;

   return (
      // ... use here
   );
}

How To Perform GET HTTP Request in React's Class Components With Axios

As we saw with functional components, we can send GET requests with Axios. All that remains is to execute the GET request within the ComponentDidMount() lifecycle and to import Axios:

import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         posts: [],
      };
   }

   componentDidMount() {
      axios
         .get('https://jsonplaceholder.typicode.com/posts')
         .then((response) => {
            this.setState({ posts: response.data });
         })
         .catch((error) => {
            console.log(error);
         });
   }

   render() {
      const { posts } = this.state;
      return (
         // ...
      );
   }
}

Conclusion

We learned how to perform GET HTTP requests with both functional and class components using the two most commonly used methods - the Fetch API and Axios, in this article.

Using a specific method is entirely up to you.

Last Updated: November 17th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms