Popular Searches
Popular Course Categories
Popular Courses

GET Requests

GET Requests

API Integration in React

GET Requests in React

A GET request is an HTTP request used to retrieve data from a server or API. In React applications, GET requests are commonly used to display user profiles, product lists, blog posts, weather information, and other dynamic data.

Learn more: JustAcademy React JS Training | Register for React JS Course Demo


1. What Is a GET Request?

A GET request asks a server to return information about a resource. It is one of the most frequently used HTTP methods in web development.

For example, an online shopping application might send a GET request to retrieve all available products from a server.

GET https://api.example.com/products

The server processes the request and returns a response, often containing JSON data that React can display in the user interface.

Common Uses of GET Requests

  • Fetching a list of users.
  • Displaying products and product details.
  • Loading blog posts and articles.
  • Retrieving dashboard statistics.
  • Showing weather information from an API.
  • Loading data according to search terms, filters, or pagination.

2. How a GET Request Works in React

  1. The React component needs data from a server.
  2. The application sends a GET request to an API endpoint.
  3. The server processes the request and returns a response.
  4. The application checks whether the request succeeded.
  5. The response data is stored in React state.
  6. React re-renders the component and displays the retrieved information.

Request Flow

React Component
      |
      v
Send GET Request
      |
      v
API Server
      |
      v
Return JSON Response
      |
      v
Store Data in React State
      |
      v
Display Data in UI

3. Using the Fetch API for GET Requests

The Fetch API is a built-in JavaScript feature that allows applications to make HTTP requests. It can be used directly in React without installing an additional package.

Basic Syntax

fetch("https://api.example.com/products")
  .then(response => {
    if (!response.ok) {
      throw new Error("Failed to fetch products");
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error("Error:", error);
  });

Explanation

  • fetch() sends the HTTP request.
  • response.ok checks whether the HTTP status is in the successful range.
  • response.json() reads and parses the response body as JSON.
  • then() processes the returned result.
  • catch() handles network errors and errors explicitly thrown in the promise chain.

Important: Fetch does not automatically reject its promise for HTTP errors such as 404 or 500. Check response.ok before processing the response body.


4. Making a GET Request Using Async/Await

The async/await syntax provides a cleaner way to write asynchronous JavaScript code. It makes request handling easier to read and maintain.

async function getProducts() {
  try {
    const response = await fetch(
      "https://api.example.com/products"
    );

    if (!response.ok) {
      throw new Error("Unable to fetch products");
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Request failed:", error);
  }
}

getProducts();

The await keyword pauses the execution of the async function until the promise settles. It does not block the entire browser interface.


5. GET Requests with useEffect and useState

In React, useState can store the retrieved data, while useEffect can run the request when the component appears or when its dependencies change. For more advanced applications, framework data-fetching tools or libraries such as TanStack Query can provide caching and other optimizations.

Example: Fetching Users from an API

import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    async function fetchUsers() {
      try {
        setLoading(true);
        setError("");

        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users",
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error("Failed to load users");
        }

        const data = await response.json();
        setUsers(data);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message || "Something went wrong");
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    fetchUsers();

    return () => {
      controller.abort();
    };
  }, []);

  if (loading) {
    return <p>Loading users...</p>;
  }

  if (error) {
    return <p>Error: {error}</p>;
  }

  if (users.length === 0) {
    return <p>No users found.</p>;
  }

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            {user.name} - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default Users;

Code Explanation

  • useState([]) initializes the users list as an empty array.
  • loading tracks whether the request is still in progress.
  • error stores an error message if the request fails.
  • useEffect() runs the request when the component is mounted.
  • AbortController cancels the request when the component is cleaned up.
  • users.map() displays each user in the list.
  • key={user.id} gives each rendered list item a stable key.

The example uses JSONPlaceholder, a public testing API. Its sample data is intended for practice rather than production use.


6. Handling Loading, Success, Empty, and Error States

A reliable GET request implementation should account for different request states instead of displaying a blank screen while data loads.

State Meaning Example UI
Loading The request is still running. Loading products...
Success The request completed and data is available. Display the product list.
Empty The request succeeded but returned no records. No products found.
Error The request failed or returned an unsuccessful HTTP status. Unable to load products.

Separating these states improves usability and makes problems easier to identify.


7. Sending Query Parameters with GET Requests

Query parameters let you request specific data, such as search results, a particular page, or records matching a filter.

Example URL

https://api.example.com/products?category=shoes&page=2

Example Using URLSearchParams

const params = new URLSearchParams({
  category: "shoes",
  page: "2"
});

const response = await fetch(
  `https://api.example.com/products?${params}`
);

if (!response.ok) {
  throw new Error("Unable to fetch products");
}

const data = await response.json();
console.log(data);

Using URLSearchParams helps encode query parameter values correctly. The API must support the parameters you send.


8. GET Requests Based on User Input

Search forms often use GET requests to retrieve information based on the user's input. When a search term changes, the application can request matching records.

import { useEffect, useState } from "react";

function ProductSearch() {
  const [query, setQuery] = useState("");
  const [products, setProducts] = useState([]);
  const [error, setError] = useState("");

  useEffect(() => {
    const trimmedQuery = query.trim();
    const controller = new AbortController();

    async function searchProducts() {
      if (!trimmedQuery) {
        setProducts([]);
        setError("");
        return;
      }

      try {
        setError("");

        const params = new URLSearchParams({
          q: trimmedQuery
        });

        const response = await fetch(
          `https://api.example.com/products?${params}`,
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error("Search request failed");
        }

        const data = await response.json();

        if (!controller.signal.aborted) {
          setProducts(data.products ?? data);
        }
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message);
        }
      }
    }

    searchProducts();

    return () => controller.abort();
  }, [query]);

  return (
    <div>
      <h2>Search Products</h2>
      <input
        type="text"
        value={query}
        onChange={event => setQuery(event.target.value)}
        placeholder="Enter a product name"
      />

      {error && <p>{error}</p>}

      <ul>
        {products.map(product => (
          <li key={product.id}>{product.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default ProductSearch;

Note: Replace the example endpoint with an API that supports your chosen search parameters and response format. For production search interfaces, consider debouncing requests so that a new request is not sent on every keystroke.


9. Using Axios for GET Requests

Axios is an external HTTP client library that can simplify API requests. Install it in your React project before using it.

npm install axios

Basic Axios Example

import axios from "axios";

async function fetchProducts() {
  try {
    const response = await axios.get(
      "https://api.example.com/products"
    );

    console.log(response.data);
  } catch (error) {
    console.error("Request failed:", error);
  }
}

fetchProducts();

Axios generally parses JSON responses automatically. The returned data is available through response.data.

Fetch vs. Axios

Feature Fetch API Axios
Installation Built into modern browsers Requires installation
JSON response Usually requires response.json() Usually available in response.data
HTTP error handling Check response.ok Rejects unsuccessful HTTP statuses by default
Cancellation Supports AbortController Supports AbortController through its signal option
Additional features Basic browser request API Interceptors and other HTTP-client features

10. Common HTTP Status Codes

Status Code Meaning Explanation
200 OK The request succeeded.
204 No Content The request succeeded, but there is no response body.
400 Bad Request The server rejected the request as invalid.
401 Unauthorized Authentication may be required or invalid.
403 Forbidden The server refuses access.
404 Not Found The requested resource could not be found.
429 Too Many Requests The client exceeded a request limit.
500 Internal Server Error The server encountered an error.

11. Common Mistakes in GET Requests

  • Not checking the response status: With Fetch, check response.ok before parsing the response as successful data.
  • Forgetting JSON parsing: With Fetch, call response.json() when the response contains JSON.
  • Ignoring errors: Show a useful error message when the request fails.
  • Not showing loading feedback: Users should know when data is being retrieved.
  • Using incorrect dependencies: Include every reactive value used by an effect in its dependency list.
  • Ignoring cleanup: Cancel requests or ignore outdated results when appropriate.
  • Missing list keys: Give mapped React elements stable keys, such as IDs.
  • Assuming every API has the same response shape: Check the API documentation before accessing fields.
  • Exposing secrets: Do not place private API keys or credentials in frontend source code.

12. Best Practices for GET Requests in React

  • Use async/await and try/catch for readable request handling.
  • Maintain clear loading, success, empty, and error states.
  • Use useEffect for fetching data that synchronizes with the displayed component, or use the data-fetching approach recommended by your React framework.
  • Provide correct effect dependencies and cleanup where needed.
  • Use query parameters for supported filters, search terms, and pagination.
  • Consider caching and request deduplication for frequently requested data.
  • Keep API request logic in reusable functions or custom hooks when appropriate.
  • Handle authentication and authorization securely on the server.
  • Test successful responses, empty responses, HTTP errors, and network failures.

13. Practical Project: User Directory

Objective: Create a React page that retrieves users from an API and displays their names, email addresses, and company information.

Project Requirements

  1. Fetch user records from a public or development API.
  2. Display a loading message while the request is in progress.
  3. Render each user's name and email.
  4. Show a friendly message if no users are returned.
  5. Display an error message if the request fails.
  6. Add a search field to filter the displayed users.
  7. Optionally add pagination or a refresh button.

Expected Result

User Directory
-------------------------
Search: [ Enter name... ]

1. Leanne Graham
   Email: [email protected]

2. Ervin Howell
   Email: [email protected]

3. Clementine Bauch
   Email: [email protected]

The displayed records above are illustrative. The actual output depends on the API response.


14. Interview Questions and Answers

Q1. What is a GET request?

A GET request is an HTTP method used to retrieve information from a server.

Q2. How can you make a GET request in React?

You can use the Fetch API or an HTTP client such as Axios. In a component, data fetching can be coordinated with useEffect and stored in state using useState.

Q3. Why is useEffect used for GET requests?

useEffect can synchronize a component with an external system, such as an API, when the component appears or its dependencies change.

Q4. What is the purpose of response.json()?

It reads the response body and parses it as JSON, returning a promise that resolves to the parsed value.

Q5. Does Fetch throw an error for a 404 response?

No. Fetch generally resolves normally for HTTP error statuses, so check response.ok and handle unsuccessful responses explicitly.

Q6. What is the purpose of a loading state?

It lets the application display feedback while waiting for the server response.

Q7. Why is error handling important?

It helps the application respond gracefully to network problems, server errors, and invalid responses.

Q8. What is AbortController?

AbortController provides a way to cancel supported requests, helping prevent unnecessary work when a component is no longer interested in the result.

Q9. Can a GET request include query parameters?

Yes. Query parameters can be included in the URL to request specific records, search results, or pages.

Q10. Should a GET request change server data?

GET is intended for retrieving data, not for performing state-changing operations. Use the appropriate HTTP method for actions that create, update, or delete resources.


15. Practice Exercises

  1. Fetch a list of users and display their names.
  2. Fetch products and display their names and prices.
  3. Add loading and error states to an existing GET request.
  4. Use query parameters to request a specific page of results.
  5. Create a search field that retrieves matching records from an API.
  6. Use Axios to retrieve and display a list of posts.
  7. Test your component with a successful response, an empty result, and a failed request.

16. Conclusion

GET requests are essential for building React applications that retrieve and display dynamic data. Understanding the Fetch API, Axios, async/await, React state, effect dependencies, loading states, error handling, and request cleanup helps you build reliable API integrations.

To learn more, visit JustAcademy React JS Training or Register for React JS Course Demo.

Official References

Previous Next
whatsapp