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

default-query-function.md

56 lines1.4 KB

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
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 )
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 // ...
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 // ...
52```
53​
54[//]: # 'Example'
55​
56If you ever want to override the default queryFn, you can just provide your own like you normally would.