Open History to see the last commit
1---
2id: default-query-function
3title: Default Query Function
4---
5β
6If 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:
7β
8[//]: # 'Example'
9β
10```tsx
11// Define a default query function that will receive the query key
12const defaultQueryFn = async ({ queryKey }) => {
13 const { data } = await axios.get(
14 `https://jsonplaceholder.typicode.com${queryKey[0]}`,
15 )
16 return data
17}
18β
19// provide the default query function to your app with defaultOptions
20const queryClient = new QueryClient({
21 defaultOptions: {
22 queries: {
23 queryFn: defaultQueryFn,
24 },
25 },
26})
27β
28function App() {
29 return (
30 <QueryClientProvider client={queryClient}>
31 <YourApp />
32 </QueryClientProvider>
33 )
34}
35β
36// All you have to do now is pass a key!
37function Posts() {
38 const { status, data, error, isFetching } = useQuery({ queryKey: ['/posts'] })
39β
40 // ...
41}
42β
43// You can even leave out the queryFn and just go straight into options
44function Post({ postId }) {
45 const { status, data, error, isFetching } = useQuery({
46 queryKey: [`/posts/${postId}`],
47 enabled: !!postId,
48 })
49β
50 // ...
51}
52```
53β
54[//]: # 'Example'
55β
56If you ever want to override the default queryFn, you can just provide your own like you normally would.