New

5 demos, 10+ applications, 50+ blocks, 30+ pages & much more

Documentation

Browse and explore docs

React JS — API Calls

How API Calls Work

The React JS version uses MSW (Mock Service Worker) to intercept HTTP requests in the browser. There are no server-side route.ts files. All responses are mocked via handlers in src/api/mocks/handlers/.

MSW Setup — src/api/mocks/browser.ts

The MSW worker is started in src/main.tsx before React renders, intercepting all matching fetch requests.

// src/api/mocks/browser.ts
import { setupWorker } from 'msw/browser';
import { mockHandlers } from './handlers/mock-handlers';

export const worker = setupWorker(...mockHandlers);

Global Fetcher — src/api/global-fetcher.ts

The project exports 5 fetchers — getFetcher, postFetcher, putFetcher, patchFetcher, deleteFetcher. Import the one you need and use it with SWR.

// src/api/global-fetcher.ts

const getFetcher = (url: string | Request | URL) =>
  fetch(url).then((res) => {
    if (!res.ok) {
      throw new Error('Failed to fetch the data');
    }
    return res.json();
  });

const postFetcher = (url: string, arg: any) =>
  fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(arg),
  }).then((res) => {
    if (!res.ok) {
      throw new Error('Failed to post data');
    }
    return res.json();
  });

const putFetcher = (url: string, arg: any) =>
  fetch(url, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(arg),
  }).then((res) => {
    if (!res.ok) {
      throw new Error('Failed to updated data');
    }
    return res.json();
  });

const patchFetcher = (url: string, arg: any) =>
  fetch(url, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(arg),
  }).then((res) => {
    if (!res.ok) {
      throw new Error('Failed to updated data');
    }
    return res.json();
  });

const deleteFetcher = (url: string, arg: any) =>
  fetch(url, {
    method: 'DELETE',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(arg),
  }).then((res) => {
    if (!res.ok) {
      throw new Error('Failed to delete data');
    }
    return res.json();
  });

export { getFetcher, postFetcher, putFetcher, deleteFetcher, patchFetcher };

Add a New API Handler

Create your handler file in src/api/your-feature/, then register it in mock-handlers.ts.

// src/api/ecommerce/productsdata.ts
import { http, HttpResponse } from 'msw';

export const Ecommercehandlers = [
  http.get('/api/data/eCommerce/ProductsData', () => {
    return HttpResponse.json({ status: 200, msg: 'success', data: ProductsData });
  }),
  http.post('/api/eCommerce/carts', async () => {
    return HttpResponse.json({ status: 200, msg: 'success', data: cartItems });
  }),
  http.post('/api/data/eCommerce/add', async ({ request }) => {
    const body = await request.json();
    // handle add to cart logic...
    return HttpResponse.json({ status: 200, msg: 'Success', data: cartItems });
  }),
  http.put('/api/eCommerce/carts/increment-decrementqty', async ({ request }) => {
    const body = await request.json();
    // handle qty change logic...
    return HttpResponse.json({ status: 200, msg: 'Success', data: cartItems });
  }),
  http.delete('/api/eCommerce/remove-item-carts', async ({ request }) => {
    // handle remove logic...
    return HttpResponse.json({ status: 200, msg: 'Success', data: cartItems });
  }),
];

Register in src/api/mocks/handlers/mock-handlers.ts:

import { Contacthandlers } from 'src/api/contacts/contactsdata';
import { Chathandlers } from 'src/api/chat/chatdata';
import { Ecommercehandlers } from 'src/api/ecommerce/productsdata';
import { PostHandlers } from 'src/api/userprofile/post-data';
import { UserDataHandlers } from 'src/api/userprofile/users-data';
import { Bloghandlers } from 'src/api/blog/blogdata';
// ...import your new handler here

export const mockHandlers = [
  ...Contacthandlers,
  ...Chathandlers,
  ...Ecommercehandlers,
  ...UserDataHandlers,
  ...PostHandlers,
  ...Bloghandlers,
  // ...spread your new handler here
];

Calling the API from a Component

Use standard fetch — MSW intercepts the request automatically in the browser.

import { useEffect, useState } from 'react';

export default function ProductList() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch('/api/data/eCommerce/ProductsData')
      .then(res => res.json())
      .then(data => setProducts(data));
  }, []);

  return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}