DEV Community

Coder
Coder

Posted on • Updated on

React + Fetch - HTTP GET Request Examples

Are you looking to make HTTP GET requests to an API in a React application? Then look no further, as we have got you covered. In this blog post, we will go through some examples of how to make HTTP GET requests in React using the Fetch API.

What is the Fetch API?

The Fetch API is a modern replacement for XMLHttpRequest (XHR). It provides a simple and standard way to make HTTP requests in JavaScript. The Fetch API is a promise-based API, which means that the responses are returned as promises that can be handled using async/await or then/catch.

Making HTTP GET Requests using Fetch API

Making an HTTP GET request using the Fetch API is simple. First, we need to create a new Request object, which represents the HTTP request. The Request constructor takes two parameters - the URL to make the request to and an optional object that contains any additional options.

const request = new Request(url, options);
Enter fullscreen mode Exit fullscreen mode

Next, we need to pass this request object to the Fetch function, which returns a Promise that resolves with the Response object representing the response to the request.

fetch(request)
  .then(response => {
    // handle response
  })
  .catch(error => {
    // handle error
  });
Enter fullscreen mode Exit fullscreen mode

Example 1 - Basic GET Request

Let's start with a basic example of making an HTTP GET request using the Fetch API. In this example, we are going to make a request to the JSONPlaceholder API to fetch a list of posts.

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

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

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

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we first define a state variable posts using the useState hook. We then use the useEffect hook to make the HTTP GET request to the specified URL. We pass an empty array as the second argument to useEffect, which ensures that the effect is only executed once when the component mounts.

Inside the fetch call, we chain two then methods to handle the response data. The first then method calls the json method on the response object to convert the response body to JSON. The second then method updates the posts state variable with the fetched data.

Example 2 - HTTP GET Request with Query Parameters

In some cases, we may want to pass query parameters when making an HTTP GET request. Query parameters are used to filter or paginate data. In this example, we are going to make an HTTP GET request to the same JSONPlaceholder API but with query parameters to fetch a specific post.

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

function App() {
  const [post, setPost] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts/1?_expand=user')
      .then(response => response.json())
      .then(data => setPost(data))
      .catch(error => console.log(error));
  }, []);

  return (
    <div>
      {post ? (
        <>
          <h1>{post.title}</h1>
          <p>{post.body}</p>
          <h2>Written by {post.user.name}</h2>
        </>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we fetch a specific post with an ID of 1 and expand the user information in the response by passing the query parameter _expand=user. We use the useState hook to define a state variable post. Inside the useEffect hook, we make the HTTP GET request to the specified URL and update the post state variable with the fetched data.

Example 3 - HTTP GET Request with Headers

Sometimes, we may need to send custom headers when making an HTTP GET request, such as authentication tokens or API keys. In this example, we are going to make an HTTP GET request to the same JSONPlaceholder API with a custom header.

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

function App() {
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    const options = {
      method: 'GET',
      headers: { 'Authorization': 'Bearer your-access-token' }
    };

    fetch('https://jsonplaceholder.typicode.com/todos', options)
      .then(response => response.json())
      .then(data => setTodos(data))
      .catch(error => console.log(error));
  }, []);

  return (
    <div>
      <h1>Todos</h1>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we define an options object that contains a custom Authorization header with an access token. We then pass this options object as the second argument to the fetch method. Inside the useEffect hook, we make the HTTP GET request to the specified URL and update the todos state variable with the fetched data.

Conclusion

In this blog post, we have covered some examples of making HTTP GET requests in React using the Fetch API. We have seen how to make basic HTTP GET requests, how to make HTTP GET requests with query parameters, and how to make HTTP GET requests with custom headers.

The Fetch API is a powerful tool for making HTTP requests in JavaScript. It provides a simple and standard way to make HTTP requests and handle responses. We hope that this blog post has helped you in understanding how to make HTTP GET requests in React using the Fetch API.

Top comments (0)