Skip to content

Commit 4053ef0

Browse files
author
Guillaume Labat
committed
refactor(QueryClient): add dev warning
Warn when several query defaults match a given key. Could be error prone if the returned defaults are not the expected ones. The order of registration does matter.
1 parent 6710bc1 commit 4053ef0

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

src/core/queryClient.ts

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -546,13 +546,35 @@ export class QueryClient {
546546
}
547547
}
548548

549+
findQueryDefaults(
550+
queryKey?: QueryKey
551+
): QueryOptions<any, any, any> | undefined {
552+
if (!queryKey) {
553+
return undefined
554+
}
555+
556+
// First retrieve all matching defaults for the given key
557+
const matchingDefaults = this.queryDefaults.filter(x =>
558+
partialMatchKey(queryKey, x.queryKey)
559+
)
560+
// It is ok not having defaults, but it is error prone to have more than 1 default for a given key
561+
if (process.env.NODE_ENV !== 'production' && matchingDefaults?.length > 1) {
562+
console.warn(
563+
`[QueryClient] Several defaults match with key '${JSON.stringify(
564+
queryKey
565+
)}'. The first matching query options are used. Please check how query defaults are registered. Order does matter here. cf. http://react-query.com/some/link/to/document#queryDefaults.`
566+
)
567+
}
568+
// Explicitly returns the first one
569+
const firstMatchingDefaults = matchingDefaults?.[0]
570+
return firstMatchingDefaults?.defaultOptions || undefined
571+
}
572+
549573
getQueryDefaults(
550574
queryKey?: QueryKey
551575
): QueryObserverOptions<any, any, any, any, any> | undefined {
552-
return queryKey
553-
? this.queryDefaults.find(x => partialMatchKey(queryKey, x.queryKey))
554-
?.defaultOptions
555-
: undefined
576+
const queryDefaults = this.findQueryDefaults(queryKey)
577+
return queryDefaults
556578
}
557579

558580
setMutationDefaults(

0 commit comments

Comments
 (0)