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
...args: [any]
A rest parameter capturing all arguments passed tofetcher. These arguments are forwarded directly to the nativefetchfunction.Typically, the first argument is the resource URL (string or Request object).
The optional second argument is a
RequestInitconfiguration object containing options such as method, headers, body, etc.
Returns
Promise<any>
Returns a promise that resolves with the parsed JSON data from the response body if the request succeeds.
Throws
Throws a generic
Errorwith the message'An error occurred while fetching the data.'if the HTTP response status is not OK.
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
The function uses the spread operator (
...args) to accept any number of arguments and pass them directly to the nativefetch. This allows it to be flexible and handle any validfetchinvocation signature.After awaiting the response, it checks the
okproperty of the response object, which indicates if the status code is in the successful range (200–299).If the response is not ok, the function throws a generic error. This simple error handling abstracts away response status checking from the caller.
When the response is successful,
res.json()is called and returned, which itself returns a promise resolving to the parsed JSON object.This abstraction promotes DRY principles by centralizing error handling and JSON parsing for all fetch requests in the application.
Interaction with Other System Components
This utility function is intended to be imported wherever HTTP requests are made within the application, particularly in data access layers or API service modules.
It acts as a foundational building block for services that interact with external APIs or backend endpoints, ensuring consistent error handling and response processing.
By returning parsed JSON, it simplifies the downstream logic that consumes API responses.
It can be combined with higher-level abstractions such as data caching hooks, state management, or request retry mechanisms.
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
Purpose: Simplifies fetch requests with built-in error handling and JSON parsing.
Function:
fetcherwraps nativefetch, checks response status, throws errors on failure, and returns JSON on success.Usage: Used throughout the codebase wherever HTTP requests are made.
Benefits: Centralizes error and response handling, reduces boilerplate code, improves code consistency.
This minimal but effective utility enhances maintainability and reliability of network communication in the project.