Popular Searches
Popular Course Categories
Popular Courses

Handling API Responses

Handling API Responses

API Integration in React

Handling API Responses in React

Handling API responses is an essential part of React development. When a React application communicates with a backend server, it must receive the response, check its status, process the returned data, handle errors, and update the user interface. Proper API response handling helps developers build reliable applications such as e-commerce websites, dashboards, social media platforms, and user management systems.

Course Links: JustAcademy React JS Training | Register for React JS Course Demo


1. What Is an API Response?

An API response is the information returned by a server after an application sends an HTTP request. The response usually contains a status code, response headers, and sometimes a response body containing data or an error message.

For example, a React application may send a GET request to retrieve products. The server responds with product information, which the application can display on the screen.

Example API Response

{
  "id": 101,
  "name": "Laptop",
  "price": 55000,
  "category": "Electronics"
}

This JSON response contains information about a product. React can store the parsed object in state and display its properties in the user interface.

Common Parts of an HTTP Response

  • Status code: Indicates whether the request succeeded or encountered a problem.
  • Headers: Provide metadata about the response, such as its content type.
  • Body: Contains the returned data, error details, or other content. Some responses have no body.

2. Why Is API Response Handling Important?

  • It allows applications to display dynamic data from a server.
  • It helps identify successful and unsuccessful requests.
  • It improves the user experience through loading indicators and clear messages.
  • It prevents applications from processing invalid or unexpected response data incorrectly.
  • It helps developers manage network errors and server failures.
  • It makes API integrations easier to debug, test, and maintain.

3. Understanding HTTP Status Codes

HTTP status codes describe the outcome of an HTTP request. React applications can use these codes, along with the response body, to decide what to display or how to proceed.

Status Code Meaning Typical Handling
200 OK The request succeeded. Process and display the returned data.
201 Created A resource was created successfully. Show confirmation and optionally display the created resource.
204 No Content The request succeeded without a response body. Update the interface without attempting to parse JSON.
400 Bad Request The request contains invalid information. Display an appropriate validation or request error.
401 Unauthorized Authentication is missing or invalid. Ask the user to sign in or refresh authentication as appropriate.
403 Forbidden The server refuses access. Explain that the operation is not permitted.
404 Not Found The requested resource does not exist or is unavailable. Display a not-found message.
429 Too Many Requests The client has exceeded a request limit. Respect retry guidance, including any Retry-After header.
500 Internal Server Error The server encountered an unexpected problem. Show a friendly error message and offer retry when appropriate.

Important: A status code alone does not describe the entire response. Check the API documentation to understand the response body and the behavior expected for each endpoint.


4. Handling API Responses with the Fetch API

The Fetch API is built into modern browsers and allows JavaScript applications to send HTTP requests. In React, Fetch can be used to retrieve data from an API and process the response.

Basic Example

async function fetchUser() {
  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users/1"
    );

    if (!response.ok) {
      throw new Error(
        `Request failed with status ${response.status}`
      );
    }

    const data = await response.json();
    console.log("User data:", data);
  } catch (error) {
    console.error("Error:", error.message);
  }
}

fetchUser();

Explanation

  • fetch() sends the HTTP request.
  • await waits for the request promise to settle.
  • response.ok checks whether the HTTP status is in the 200–299 range.
  • response.status provides the numerical HTTP status code.
  • response.json() reads the response body and parses it as JSON.
  • try/catch handles network errors and errors thrown by the code.

Important: Fetch normally does not reject its promise for HTTP errors such as 404 or 500. Always check response.ok when unsuccessful HTTP responses should be treated as errors.


5. Understanding response.json()

The response.json() method reads the response body and parses it as JSON. It returns a promise that resolves to the parsed JavaScript value.

Example

const response = await fetch(
  "https://jsonplaceholder.typicode.com/users/1"
);

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

const user = await response.json();

console.log(user.name);
console.log(user.email);

Key Points

  • Use response.json() when the response body contains JSON.
  • The parsed value may be an object, an array, a string, a number, or another valid JSON value.
  • Parsing fails if the response body is not valid JSON.
  • Do not call response.json() more than once on the same response body.
  • Do not attempt to parse JSON when an endpoint returns no body, such as a 204 response.

6. Handling API Responses in React with useState and useEffect

The useState Hook stores response data and request status, while useEffect can initiate a request when a component appears or when its dependencies change.

Example: Fetching and Displaying User Information

import { useEffect, useState } from "react";

function UserProfile() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

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

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

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

        if (!response.ok) {
          throw new Error(
            `Unable to load user (${response.status})`
          );
        }

        const data = await response.json();

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

    fetchUser();

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

  if (loading) {
    return <p role="status">Loading user information...</p>;
  }

  if (error) {
    return <p role="alert">Error: {error}</p>;
  }

  if (!user) {
    return <p>User information is unavailable.</p>;
  }

  return (
    <div>
      <h2>{user.name}</h2>
      <p>Email: {user.email}</p>
      <p>Phone: {user.phone}</p>
      <p>Website: {user.website}</p>
    </div>
  );
}

export default UserProfile;

How It Works

  1. The component initializes user data, loading status, and error state.
  2. The effect sends a request when the component mounts.
  3. The code checks the HTTP status before processing the response body.
  4. The JSON response is stored in the user state.
  5. If an error occurs, the component stores an error message.
  6. The UI displays loading, error, unavailable, or success content as appropriate.
  7. The cleanup function cancels the request if it is still in progress when the effect is cleaned up.

This example uses JSONPlaceholder, a sample API for learning and testing. Use your own API endpoint when developing a production application.


7. Handling Different API Response Formats

Not every API returns the same JSON structure. Some endpoints return a single object, while others return an array or an object containing a data collection and metadata.

Example A: Single Object

{
  "id": 1,
  "name": "Rahul",
  "email": "[email protected]"
}
const user = await response.json();
console.log(user.name);

Example B: Array of Objects

[
  { "id": 1, "name": "Rahul" },
  { "id": 2, "name": "Priya" }
]
const users = await response.json();

users.forEach(user => {
  console.log(user.name);
});

Example C: Nested Data

{
  "success": true,
  "data": {
    "id": 101,
    "name": "Laptop"
  },
  "message": "Product retrieved successfully"
}
const result = await response.json();

console.log(result.success);
console.log(result.data.name);
console.log(result.message);

Example D: Paginated Response

{
  "data": [
    { "id": 1, "name": "Rahul" },
    { "id": 2, "name": "Priya" }
  ],
  "page": 1,
  "totalPages": 5,
  "totalItems": 50
}
const result = await response.json();

console.log(result.data);
console.log(result.page);
console.log(result.totalPages);

Best Practice: Always inspect the API documentation or a real sample response before accessing properties. Do not assume that every endpoint returns an array or contains a data property.


8. Handling Empty Responses

Some APIs return an empty response body when an operation succeeds. For example, a DELETE request or an update operation may return status 204 No Content.

Example

async function deleteUser(id) {
  const response = await fetch(
    `https://api.example.com/users/${id}`,
    { method: "DELETE" }
  );

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

  if (response.status === 204) {
    return null;
  }

  const contentType = response.headers.get("content-type");

  if (contentType?.includes("application/json")) {
    return response.json();
  }

  return response.text();
}

This function checks the response status and avoids parsing JSON when the response is 204. For other statuses, it processes the body according to the response content type.

Note: Use the response format documented by the API. A content type check is helpful, but it does not replace proper validation of the response structure.


9. Handling API Errors

API errors may occur because of network problems, invalid requests, authentication failures, missing resources, or server issues. React applications should handle these situations gracefully.

Example: Reading an Error Response

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

  if (!response.ok) {
    let message = `Request failed (${response.status})`;

    try {
      const errorData = await response.json();
      message = errorData.message || message;
    } catch {
      // The response body may be empty or not JSON.
    }

    throw new Error(message);
  }

  return response.json();
}

Common Error Types

  • Network error: The browser could not complete the request.
  • HTTP error: The server returned an unsuccessful status code.
  • Parsing error: The response body was not valid JSON.
  • Data-shape error: The response did not contain the properties expected by the application.
  • Authentication error: The request lacks valid authentication.

Present user-friendly messages in the UI and keep detailed diagnostic information in suitable development logs or protected monitoring systems.


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

A well-designed React component should clearly communicate the current status of an API request.

State Meaning Example UI
Loading The request is still in progress. 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 status. Unable to load products.

Example: Conditional Rendering

if (loading) {
  return <p role="status">Loading...</p>;
}

if (error) {
  return <p role="alert">{error}</p>;
}

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

return (
  <ul>
    {items.map(item => (
      <li key={item.id}>{item.name}</li>
    ))}
  </ul>
);

These conditions make the UI easier to understand and prevent an empty response from being mistaken for a failed request.


11. Handling API Responses with Axios

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

npm install axios

Example

import axios from "axios";

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

    console.log("Status:", response.status);
    console.log("Headers:", response.headers);
    console.log("Data:", response.data);
  } catch (error) {
    if (error.response) {
      console.error(
        "Server responded with:",
        error.response.status
      );
      console.error("Response data:", error.response.data);
    } else if (error.request) {
      console.error("No response received:", error.message);
    } else {
      console.error("Request setup error:", error.message);
    }
  }
}

fetchProducts();

Important Axios Properties

Property Description
response.data The response body, usually parsed automatically when it contains JSON.
response.status The numerical HTTP status code.
response.statusText The HTTP status text when provided.
response.headers Response headers.
error.response Available when the server returned a response Axios treats as unsuccessful.
error.request Available when a request was made but no response was received.

Axios rejects unsuccessful HTTP statuses by default, unlike Fetch, which generally resolves normally for statuses such as 404 and 500. Axios behavior can be customized through configuration.


12. Transforming and Filtering API Response Data

Sometimes an API returns more information than the UI needs. You can transform, filter, or sort the response data before storing it in React state.

Example: Filtering Active Users

const response = await fetch(
  "https://api.example.com/users"
);

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

const users = await response.json();

const activeUsers = users.filter(
  user => user.active === true
);

setUsers(activeUsers);

Example: Extracting Required Fields

const response = await fetch(
  "https://api.example.com/products"
);

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

const products = await response.json();

const simplifiedProducts = products.map(product => ({
  id: product.id,
  name: product.title,
  price: product.price
}));

setProducts(simplifiedProducts);

Transforming data can make components easier to maintain by allowing the UI to work with a consistent data structure.


13. Handling Unexpected or Invalid Data

A successful HTTP response does not guarantee that the returned data matches what the component expects. Validate important data before using it.

Example

function isProductList(value) {
  return (
    Array.isArray(value) &&
    value.every(product =>
      product !== null &&
      typeof product === "object" &&
      typeof product.id === "number" &&
      typeof product.title === "string"
    )
  );
}

async function fetchProducts() {
  const response = await fetch(
    "https://dummyjson.com/products"
  );

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

  const result = await response.json();
  const products = result.products;

  if (!isProductList(products)) {
    throw new Error("Unexpected product data format");
  }

  return products;
}

Validation is especially useful when the API contract is important or data comes from external services. For larger projects, consider schema validation tools such as Zod.


14. Avoiding Stale API Responses

When a component sends multiple requests, responses may arrive in a different order from the order in which requests were sent. If an older response updates state after a newer response, the UI may display outdated data. This is known as a race condition.

Example Using AbortController

import { useEffect, useState } from "react";

function SearchUsers({ query }) {
  const [users, setUsers] = useState([]);
  const [error, setError] = useState("");

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

    async function search() {
      try {
        setError("");

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

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

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

        const data = await response.json();

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

    search();

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

  if (error) {
    return <p role="alert">{error}</p>;
  }

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default SearchUsers;

When the query changes or the component unmounts, cleanup aborts the previous request if it is still running. Depending on the application, a data-fetching library can also manage caching, request deduplication, retries, and stale results.


15. Best Practices for Handling API Responses

  • Check HTTP status codes before treating a response as successful.
  • Parse the response body according to its actual content type and documented format.
  • Handle empty responses, including 204 No Content.
  • Use loading, success, empty, and error states where appropriate.
  • Validate important fields before using external data.
  • Use try/catch to handle network, parsing, and application errors.
  • Cancel requests or ignore stale results when request parameters change.
  • Keep API logic reusable and separate from presentation code when practical.
  • Avoid displaying sensitive technical details to users.
  • Use HTTPS and enforce authentication and authorization on the backend.
  • Test success responses, error responses, empty bodies, malformed data, and network failures.
  • For complex data fetching, consider framework-supported approaches or libraries such as TanStack Query or SWR.

16. Practical Project: API-Based Product Dashboard

Objective: Create a React dashboard that retrieves products from an API, processes the response, and displays the results with appropriate status messages.

Project Requirements

  1. Send a GET request to retrieve product information.
  2. Check the response status before processing the body.
  3. Parse the JSON response.
  4. Display product names, prices, and categories.
  5. Show a loading indicator while the request is running.
  6. Display an error message when the request fails.
  7. Show an empty-state message when no products are available.
  8. Validate the response structure before using it.
  9. Add a Retry button for recoverable failures.
  10. Ensure outdated requests do not overwrite newer results.

Example API Response

{
  "products": [
    {
      "id": 1,
      "title": "Laptop",
      "price": 55000,
      "category": "electronics"
    },
    {
      "id": 2,
      "title": "Headphones",
      "price": 2500,
      "category": "accessories"
    }
  ],
  "total": 2
}

Expected UI

Product Dashboard
-------------------------
Laptop
Price: 55000
Category: electronics

Headphones
Price: 2500
Category: accessories

The example output is illustrative. The actual results depend on the API response.


17. Common Interview Questions and Answers

Q1. What is an API response?

An API response is the information returned by a server after an HTTP request. It can include a status code, headers, and a response body.

Q2. What is response.json() used for?

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

Q3. What does response.ok indicate?

It is a Boolean property that is true when the HTTP status code is between 200 and 299.

Q4. Does Fetch automatically throw an error for a 404 response?

No. Fetch usually resolves with a Response object for HTTP error statuses. You must check response.ok and handle unsuccessful responses explicitly.

Q5. How does Axios handle API responses?

Axios returns a response object that includes properties such as data, status, and headers. It rejects unsuccessful HTTP statuses by default.

Q6. What is the difference between response data and response headers?

Response data contains the body returned by the server, while response headers provide metadata about the response.

Q7. How should a 204 response be handled?

Check the status and do not attempt to parse JSON if the response has no body.

Q8. What is a race condition in API fetching?

A race condition occurs when multiple requests finish in an unexpected order and an older response overwrites newer data.

Q9. Why should API response data be validated?

Validation helps prevent errors when the server returns unexpected fields, types, or data structures.

Q10. How do you handle API errors in React?

Check HTTP statuses, catch network and parsing errors, store an appropriate message in state, and render a helpful error interface.


18. Practice Exercises

  1. Fetch a user object and display its name and email.
  2. Fetch a list of products and render it using map().
  3. Display the HTTP status code in the browser console.
  4. Handle a 404 response and display a suitable error message.
  5. Handle a 204 response without attempting to parse JSON.
  6. Transform an API response to display only selected fields.
  7. Validate the structure of a response before storing it in state.
  8. Add loading, empty, success, and error states to a data-fetching component.
  9. Use Axios to retrieve data and handle both server responses and network errors.
  10. Prevent stale search responses from overwriting newer results.

19. Conclusion

Handling API responses is a fundamental React skill. Developers need to understand HTTP status codes, response headers, JSON parsing, error handling, data validation, loading states, and request cleanup. Applying these concepts helps create React applications that retrieve information reliably and provide clear feedback to users.

Learn more through JustAcademy React JS Training or Register for React JS Course Demo.

Official References

Previous Next
whatsapp