fetch.ts

Overview

The fetch.ts file exports a single asynchronous utility function named fetcher. This function is designed to simplify making HTTP requests using the native fetch API by encapsulating common error handling and JSON response parsing logic. Its primary purpose is to serve as a reusable, minimal wrapper that standardizes how data fetching is performed across the application, ensuring consistent error management and response processing.


Detailed Explanation

fetcher(...args: [any]) : Promise<any>

Description

fetcher is an asynchronous function that internally calls the native fetch() function with the provided arguments. It checks the HTTP response status, throws an error if the response is not successful (i.e., status code outside the 200–299 range), and otherwise parses and returns the response body as JSON.

Parameters

Returns

Throws

Usage Example

import fetcher from './fetch';

// Example: GET request
async function getUserData(userId: string) {
  try {
    const userData = await fetcher(`/api/users/${userId}`);
    console.log(userData);
  } catch (error) {
    console.error('Failed to fetch user data:', error);
  }
}

// Example: POST request with options
async function createUser(userData: object) {
  try {
    const createdUser = await fetcher('/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(userData),
    });
    return createdUser;
  } catch (error) {
    console.error('User creation failed:', error);
  }
}

Implementation Details


Interaction with Other System Components


Visual Diagram

flowchart TD
    A[fetcher(...args)] --> B[fetch(...args)]
    B --> C{res.ok?}
    C -- Yes --> D[res.json() → Promise<JSON>]
    C -- No --> E[Throw Error('An error occurred while fetching the data.')]
    D --> F[Return parsed JSON]

Summary

This minimal but effective utility enhances maintainability and reliability of network communication in the project.