Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 21x 1x 1x 492x 492x 85x 85x 85x 83x 1x 1x 82x | import { useCallback } from 'react'
import { useAuth } from './auth'
export const API_BASE = (import.meta.env.VITE_API_BASE ?? '') + '/api/v1'
export class SessionExpiredError extends Error {
constructor() {
super('Session expired')
this.name = 'SessionExpiredError'
}
}
export function useApi() {
const { token, signOut } = useAuth()
return useCallback(
async (path: string, init: RequestInit = {}): Promise<Response> => {
const headers = new Headers(init.headers)
if (token) headers.set('authorization', `Bearer ${token}`)
const res = await fetch(`${API_BASE}${path}`, { ...init, headers })
if (res.status === 401 || res.status === 403) {
signOut()
throw new SessionExpiredError()
}
return res
},
[token, signOut],
)
}
|