Docs
Utilities
Fetch Utility

Fetch Utility

You will learn how to use the fetchCall utility located at utils/fetch.js.

The fetchCall function is an asynchronous utility for making HTTP requests. It simplifies API interactions with features like default headers, error handling, and toast notifications, making it a better choice than using fetch directly in most cases.

In Next.js, using fetch is recommended over libraries like Axios because it is lightweight, built into the platform, and optimized for server-side rendering (SSR) and static site generation (SSG). fetch also works seamlessly on both the client and server, with built-in polyfills and fewer dependencies.

By extending fetch, fetchCall provides additional conveniences, making API calls faster and more consistent while staying aligned with Next.js best practices.

Usage

Base URL

The base URL is set as /api, so you can omit it when specifying endpoints. For example, use /endpoints/myurl instead of api/endpoints/myurl.

Examples

GET Request

import fetchCall from '@/utils/fetch';
 
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

import fetchCall from '@/utils/fetch';
 
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 handles common HTTP errors with toast notifications:

  • 401 Unauthorized: Displays a notification prompting the user to log in.
  • 404 Not Found: Displays a notification indicating the resource was not found.
  • 500 Internal Server Error: Displays a notification about server issues.

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 streamline your API interactions with robust error handling and user feedback, enhancing your app's reliability and user experience.