Created
January 20, 2025 15:44
-
-
Save sirius0486/8c4f6e12ccf4269cb4334f6263e854f6 to your computer and use it in GitHub Desktop.
useSWR snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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