Module: API Integration

Using Fetch API

This document outlines how to integrate with APIs in React using the built-infetchAPI.

What is the Fetch API?

ThefetchAPI is a modern interface for making network requests such as retrieving data from a server. It is promise-based, making asynchronous operations cleaner and easier to manage, and it replaces the olderXMLHttpRequestobject.

Basic Fetch Usage

The corefetchfunction takes the API URL as its first argument and returns a Promise that resolves to aResponseobject.


fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });

Explanation:

  1. fetch(url)initiates a GET request to the API.
  2. response.okchecks if the response status is successful (200–299).
  3. response.json()parses the response body as JSON.
  4. .then(data)handles the parsed response data.
  5. .catch(error)handles network or parsing errors.

Integrating Fetch into a React Component

Below is a simple React component that fetches data and displays it:


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

function DataFetcher() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');

        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.body}</p>
    </div>
  );
}

export default DataFetcher;

Explanation:

  1. State Variables:
    • datastores fetched data.
    • loadingtracks loading state.
    • errorstores error details.
  2. useEffect:
    • Runs once on component mount.
    • Encapsulates fetch logic usingasync/await.
    • Handles success, failure, and cleanup viatry...catch...finally.
  3. Conditional Rendering:
    • Shows loading text while fetching.
    • Shows error message if fetch fails.
    • Displays API data on success.

Fetch Options (POST, PUT, DELETE, Headers)

You can customize requests using an options object:


fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'My New Post',
    body: 'This is the content of my post.',
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Common Options:

  • method: HTTP method (GET, POST, PUT, DELETE).
  • headers: Request headers (e.g., Content-Type, Authorization).
  • body: Request payload (stringified JSON).
  • mode: Request mode (cors, no-cors).
  • cache: Cache behavior.

Error Handling Best Practices

  • Always checkresponse.ok.
  • Usetry...catchfor async requests.
  • Store and display error state.
  • Handle specific HTTP error codes when needed.

Alternatives to Fetch

  • Axios:Feature-rich, automatic JSON parsing, interceptors.
  • SuperAgent:Fluent API for HTTP requests.
  • Ky:Lightweight modern fetch wrapper.