New

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

Documentation

Browse and explore docs

API Calls

1. How does it work?

All fetcher functions are configured in: app/api/global-fetcher.ts

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

// app/api/global-fetcher.ts

const getFetcher = (url: string) =>
  fetch(url, {
    method: 'GET',
    headers: { browserrefreshed: 'false' },
  }).then((res) => {
    if (!res.ok) {
      throw new Error('Failed to fetch the data')
    }
    return res.json()
  })

const postFetcher = (url: string, arg: unknown) =>
  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: unknown) =>
  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: unknown) =>
  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: unknown) =>
  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 }

2. Route Handler (route.ts)

Each API lives in its own folder under app/api/ as a route.ts file using Next.js NextResponse.

// app/api/chat/route.ts
import { NextResponse } from 'next/server'

export async function GET() {
  try {
    return NextResponse.json({ status: 200, msg: 'success', data: ChatData })
  } catch (error: unknown) {
    return NextResponse.json({ status: 200, msg: 'failed', data: error })
  }
}

export async function POST(req: Request) {
  try {
    const { chatId, message } = (await req.json()) as {
      chatId: number | string
      message: string
    }
    // handle logic...
    return NextResponse.json({ status: 201, msg: 'Success', data: ChatData })
  } catch (error: unknown) {
    return NextResponse.json({ status: 400, msg: 'failed', error: 'Failed to add message' })
  }
}

3. Using SWR in a Component

Import useSWR and a fetcher from global-fetcher.ts, then call the API route path.

import useSWR from 'swr';
import { getFetcher } from '@/app/api/global-fetcher';

const API_URL = '/api/chat'; // matches app/api/chat/route.ts

export const useChats = () => {
  const { data, error } = useSWR(API_URL, getFetcher);

  return {
    data,
    error,
    isLoading: !data && !error,
  };
};

// use data in JSX
{data && Object.keys(data).map((key, index) => (
  <div key={index}>...</div>
))}