forked from CredenceOrg/Credence-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseQuery.ts
More file actions
87 lines (75 loc) · 2.2 KB
/
Copy pathuseQuery.ts
File metadata and controls
87 lines (75 loc) · 2.2 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { useCallback, useEffect, useRef, useState } from 'react'
export interface UseQueryOptions {
enabled?: boolean
}
export interface UseQueryResult<T> {
data: T | undefined
isLoading: boolean
error: Error | null
refetch: () => Promise<void>
}
/**
* A custom hook that wraps an asynchronous query function.
* Automatically handles loading, error, and data states.
* Safely prevents state updates on unmounted components.
* Query execution (both initial and refetch) is disabled when offline.
*/
export function useQuery<T>(
queryFn: () => Promise<T>,
options: UseQueryOptions = {}
): UseQueryResult<T> {
const { enabled = true } = options
const [data, setData] = useState<T | undefined>(undefined)
const [error, setError] = useState<Error | null>(null)
const [isLoading, setIsLoading] = useState<boolean>(enabled)
const mountedRef = useRef(true)
const runIdRef = useRef(0)
const fnRef = useRef(queryFn)
// Keep the function ref fresh without causing re-renders
useEffect(() => {
fnRef.current = queryFn
})
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
const refetch = useCallback(async () => {
// Disable when offline
if (typeof window !== 'undefined' && !window.navigator.onLine) {
return
}
const currentRunId = ++runIdRef.current
setIsLoading(true)
setError(null)
try {
const result = await fnRef.current()
if (mountedRef.current && currentRunId === runIdRef.current) {
setData(result)
setError(null)
}
} catch (err) {
if (mountedRef.current && currentRunId === runIdRef.current) {
setError(err instanceof Error ? err : new Error(String(err)))
}
} finally {
if (mountedRef.current && currentRunId === runIdRef.current) {
setIsLoading(false)
}
}
}, [])
useEffect(() => {
if (enabled) {
// Check offline status before initial fetch
if (typeof window !== 'undefined' && !window.navigator.onLine) {
setIsLoading(false)
return
}
void refetch()
} else {
setIsLoading(false)
}
}, [enabled, refetch])
return { data, error, isLoading, refetch }
}