Docs
Utilities
Fetch Utility

Fetch Utility

This document provides an overview of the fetchCall utility function located at utils/fetch.js. This utility simplifies making API calls by setting default headers, handling errors, and providing user feedback through toast notifications.

Function Overview

fetchCall

The fetchCall function is an asynchronous utility for making HTTP requests. It includes built-in handling for common response statuses and user notifications.

Usage

Importing the Utility

To use the fetchCall function in your project, import it as follows:

import fetchCall from '@/utils/fetch';

Base URL

Since the fetchCall utility function sets the base URL as /api, you don't need to include /api/ at the beginning of the API endpoint. For example, instead of using api/payments/lemonsqueezy/customer-portal, you can use /payments/lemonsqueezy/customer-portal.

Making an API Call

GET Request

Here's an example of how to make a GET request using the fetchCall utility:

const fetchData = async () => {
    try {
        const data = await fetchCall('/example-endpoint');
        console.log('Data received:', data);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};
 
fetchData();

POST Request

To make a POST request with a JSON body:

const postData = async () => {
    try {
        const payload = { key: 'value' };
        const data = await fetchCall('/example-endpoint', {
            method: 'POST',
            body: payload
        });
        console.log('Data received:', data);
    } catch (error) {
        console.error('Error posting data:', error);
    }
};
 
postData();

Error Handling

The fetchCall utility includes error handling for common HTTP statuses:

  • 401 Unauthorized: Displays a toast notification with a "Login Error" message and redirects the user to the login page.
  • 403 Forbidden: Displays a toast notification indicating that the user is not authorized.
  • Other Errors: Displays a generic error message or a specific error message if provided by the API response.

Example of handling errors:

try {
    const data = await fetchCall('/example-endpoint');
    console.log('Data received:', data);
} catch (error) {
    // Error handling is already done in fetchCall; additional handling can be done here if needed
    console.error('Fetch call failed:', error);
}

Notifications

The fetchCall utility uses react-hot-toast for displaying error notifications. The Toaster component from react-hot-toast is set up in UtilityComponents located at utils/components/UtilityComponents.js.

By using the fetchCall utility, you can streamline your API interactions with consistent error handling and user notifications, improving the overall robustness and user experience of your application.