initial commit
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
45
src/admin/hooks/useApiCall.ts
Normal file
45
src/admin/hooks/useApiCall.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { useCallback, useRef } from 'react'
|
||||
import { useAlert } from '../context/AlertContext'
|
||||
import apiFetch from '../utils/api'
|
||||
|
||||
interface ApiCallResult<T> {
|
||||
data: T | null
|
||||
ok: boolean
|
||||
response: Response | null
|
||||
}
|
||||
|
||||
export default function useApiCall() {
|
||||
const alert = useAlert()
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
const call = useCallback(async <T = unknown>(
|
||||
url: string,
|
||||
options: RequestInit = {},
|
||||
errorMsg = 'Chyba při načítání dat'
|
||||
): Promise<ApiCallResult<T>> => {
|
||||
if (abortRef.current) abortRef.current.abort()
|
||||
const controller = new AbortController()
|
||||
abortRef.current = controller
|
||||
|
||||
try {
|
||||
const response = await apiFetch(url, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
})
|
||||
const data = await response.json()
|
||||
if (!response.ok || !data.success) {
|
||||
alert.error(data.error || errorMsg)
|
||||
return { data: null, ok: false, response }
|
||||
}
|
||||
return { data: data.data as T, ok: true, response }
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.name === 'AbortError') {
|
||||
return { data: null, ok: false, response: null }
|
||||
}
|
||||
alert.error(errorMsg)
|
||||
return { data: null, ok: false, response: null }
|
||||
}
|
||||
}, [alert])
|
||||
|
||||
return { call }
|
||||
}
|
||||
Reference in New Issue
Block a user