Default Query Function

· abundance's blog


If you find yourself wishing for whatever reason that you could just share the same query function for your entire app and just use query keys to identify what it should fetch, you can do that by providing a default query function to TanStack Query:

 1// Define a default query function that will receive the query key
 2const defaultQueryFn = async ({ queryKey }) => {
 3  const { data } = await axios.get(
 4    `https://jsonplaceholder.typicode.com${queryKey[0]}`,
 5  )
 6  return data
 7}
 8
 9// provide the default query function to your app with defaultOptions
10const queryClient = new QueryClient({
11  defaultOptions: {
12    queries: {
13      queryFn: defaultQueryFn,
14    },
15  },
16})
17
18function App() {
19  return (
20    <QueryClientProvider client={queryClient}>
21      <YourApp />
22    </QueryClientProvider>
23  )
24}
25
26// All you have to do now is pass a key!
27function Posts() {
28  const { status, data, error, isFetching } = useQuery({ queryKey: ['/posts'] })
29
30  // ...
31}
32
33// You can even leave out the queryFn and just go straight into options
34function Post({ postId }) {
35  const { status, data, error, isFetching } = useQuery({
36    queryKey: [`/posts/${postId}`],
37    enabled: !!postId,
38  })
39
40  // ...
41}

If you ever want to override the default queryFn, you can just provide your own like you normally would.