Skip to content

Instantly share code, notes, and snippets.

@sirius0486
Created January 20, 2025 15:44
Show Gist options
  • Save sirius0486/8c4f6e12ccf4269cb4334f6263e854f6 to your computer and use it in GitHub Desktop.
Save sirius0486/8c4f6e12ccf4269cb4334f6263e854f6 to your computer and use it in GitHub Desktop.
useSWR snippet
// types.ts
export interface User {
id: string;
name: string;
email: string;
}
export interface Post {
id: string;
title: string;
body: string;
}
// api.ts
export const fetcher = async <T>(
url: string,
options: RequestInit = {}
): Promise<T> => {
const token = localStorage.getItem('accessToken');
const headers = {
'Content-Type': 'application/json',
Authorization: token ? `Bearer ${token}` : '',
...options.headers,
};
const config: RequestInit = {
method: options.method || 'GET',
headers,
...options,
};
if (['POST', 'PUT', 'PATCH'].includes(config.method || 'GET') && options.body) {
config.body = JSON.stringify(options.body);
}
const response = await fetch(url, config);
if (!response.ok) {
const error = new Error('An error occurred while fetching the data.');
(error as any).status = response.status;
throw error;
}
return response.json() as Promise<T>;
};
// hooks/useUsers.ts
import useSWR from 'swr';
import { API_ENDPOINTS, fetcher } from '../api';
import { User } from '../types';
export function useUsers() {
const { data, error, isLoading } = useSWR<User[]>(API_ENDPOINTS.getUsers, fetcher);
return {
users: data,
isLoading,
isError: error,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment