-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathQueryErrorResetBoundary.tsx
More file actions
109 lines (95 loc) · 2.64 KB
/
QueryErrorResetBoundary.tsx
File metadata and controls
109 lines (95 loc) · 2.64 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
'use client'
import * as React from 'react'
import { useQueryClient } from './QueryClientProvider'
// CONTEXT
export type QueryErrorResetFunction = () => void
export type QueryErrorIsResetFunction = () => boolean
export type QueryErrorClearResetFunction = () => void
export interface QueryErrorResetBoundaryValue {
clearReset: QueryErrorClearResetFunction
isReset: QueryErrorIsResetFunction
reset: QueryErrorResetFunction
register: (queryHash: string) => void
}
function createValue(): QueryErrorResetBoundaryValue {
let isReset = false
return {
clearReset: () => {
isReset = false
},
reset: () => {
isReset = true
},
isReset: () => {
return isReset
},
register: () => {},
}
}
const QueryErrorResetBoundaryContext = React.createContext(createValue())
// HOOK
export const useQueryErrorResetBoundary = () =>
React.useContext(QueryErrorResetBoundaryContext)
// COMPONENT
export type QueryErrorResetBoundaryFunction = (
value: QueryErrorResetBoundaryValue,
) => React.ReactNode
export interface QueryErrorResetBoundaryProps {
children: QueryErrorResetBoundaryFunction | React.ReactNode
}
export const QueryErrorResetBoundary = ({
children,
}: QueryErrorResetBoundaryProps) => {
const client = useQueryClient()
const registeredQueries = React.useRef(new Set<string>())
const [value] = React.useState(() => {
const boundary = createValue()
return {
...boundary,
reset: () => {
boundary.reset()
const queryHashes = new Set(registeredQueries.current)
registeredQueries.current.clear()
void client.refetchQueries({
predicate: (query) =>
queryHashes.has(query.queryHash) && query.state.status === 'error',
type: 'active',
})
},
register: (queryHash: string) => {
registeredQueries.current.add(queryHash)
},
}
})
return (
<QueryErrorResetBoundaryContext.Provider value={value}>
{typeof children === 'function' ? children(value) : children}
</QueryErrorResetBoundaryContext.Provider>
)
}
/**
* @internal
*/
export function getQueryHash(query: any): string | undefined {
if (typeof query === 'object' && query !== null) {
if ('queryHash' in query) {
return query.queryHash
}
if (
'promise' in query &&
query.promise &&
typeof query.promise === 'object' &&
'queryHash' in query.promise
) {
return query.promise.queryHash
}
}
return undefined
}
export function useTrackQueryHash(query: any) {
const { register } = useQueryErrorResetBoundary()
const hash = getQueryHash(query)
if (hash) {
register(hash)
}
}