Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

config.js

96 lines2.3 KB

1import React from 'react'
2import { noop, stableStringify, identity, deepEqual } from './utils'
3​
4export const configContext = React.createContext()
5​
6const DEFAULTS = {
7 retry: 3,
8 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
9 staleTime: 0,
10 cacheTime: 5 * 60 * 1000,
11 refetchAllOnWindowFocus: true,
12 refetchInterval: false,
13 suspense: false,
14 queryKeySerializerFn: defaultQueryKeySerializerFn,
15 queryFnParamsFilter: identity,
16 throwOnError: false,
17 useErrorBoundary: undefined, // this will default to the suspense value
18 onMutate: noop,
19 onSuccess: noop,
20 onError: noop,
21 onSettled: noop,
22 refetchOnMount: true,
23 isDataEqual: deepEqual,
25​
26export const defaultConfigRef = {
27 current: DEFAULTS,
29​
30export function useConfigContext() {
31 return React.useContext(configContext) || defaultConfigRef.current
33​
34export function ReactQueryConfigProvider({ config, children }) {
35 let configContextValue = React.useContext(configContext)
36​
37 const newConfig = React.useMemo(() => {
38 const newConfig = {
39 ...(configContextValue || defaultConfigRef.current),
40 ...config,
41 }
42​
43 // Default useErrorBoundary to the suspense value
44 if (typeof newConfig.useErrorBoundary === 'undefined') {
45 newConfig.useErrorBoundary = newConfig.suspense
46 }
47​
48 return newConfig
49 }, [config, configContextValue])
50​
51 React.useEffect(() => {
52 // restore previous config on unmount
53 return () => {
54 defaultConfigRef.current = { ...(configContextValue || DEFAULTS) }
55​
56 // Default useErrorBoundary to the suspense value
57 if (typeof defaultConfigRef.current.useErrorBoundary === 'undefined') {
58 defaultConfigRef.current.useErrorBoundary =
59 defaultConfigRef.current.suspense
60 }
61 }
62 }, [configContextValue])
63​
64 if (!configContextValue) {
65 defaultConfigRef.current = newConfig
66 }
67​
68 return (
69 <configContext.Provider value={newConfig}>
70 {children}
71 </configContext.Provider>
72 )
74​
75export function defaultQueryKeySerializerFn(queryKey) {
76 if (!queryKey) {
77 return []
78 }
79​
80 if (typeof queryKey === 'function') {
81 try {
82 return defaultQueryKeySerializerFn(queryKey())
83 } catch {
84 return []
85 }
86 }
87​
88 if (typeof queryKey === 'string') {
89 queryKey = [queryKey]
90 }
91​
92 const queryHash = stableStringify(queryKey)
93 queryKey = JSON.parse(queryHash)
94​
95 return [queryHash, queryKey]