React + Fetch - HTTP GET Request Examples

    Apr 10, 2023       by Pankaj Kumar

Fetch API is one of the fastest way to make HTTP request from browser level application.It is much simpler and clear which used Promises to deliver many flexible features to make HTTP requests to server from the browser level application. It is available in the global scope that directs the browsers to make a request to a URL.

There are different ways by which we can make GET Requests, here are some examples of how to use fetch() to make HTTP GET requests in a React application:

Example 1: Basic GET request

 

 
fetch('https://jsonplaceholder.typicode.com/todos')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
 

 

In this example, we're using fetch() to make a GET request to the JSONPlaceholder API. The response gets converted to JSON format with the help json() method, and the final data is printed(logged) to the console. If there's an error with the request, we'll log that to the console as well.

 

Example 2: Using async/await

 

 
async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
 
fetchData();
 

 

This example uses async/await syntax to make the request and handle the response. The fetchData() function is declared as async so that we can use await to wait for the response to come back. Once we have the response, we convert it to JSON using response.json() and log the resulting data to the console. If there's an error, we'll catch it and log it to the console.

Example 3: Passing query parameters

 

 
const userId = 1;
 
fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
 

 

In this example, we're making a GET request to the JSONPlaceholder API with a query parameter of userId. We're using template literals to interpolate the userId variable into the URL string. The resulting data is logged to the console, and any errors are caught and logged as well.

I hope these examples help you get started with making HTTP GET requests in your React application using fetch()!

 

Thank you!


Find other similar Articles here: