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

default-query-function.md

50 lines1.1 KB

1---
2id: default-query-function
3title: Default Query Function
4ref: docs/framework/react/guides/default-query-function.md
5---
6​
7[//]: # 'Example'
8​
9```ts
10// Define a default query function that will receive the query key
11const defaultQueryFn: QueryFunction = async ({ queryKey }) => {
12 const { data } = await axios.get(
13 `https://jsonplaceholder.typicode.com${queryKey[0]}`,
14 )
15 return data
17​
18// provide the default query function to your app with defaultOptions
19const createQueryClient = () =>
20 new QueryClient({
21 defaultOptions: {
22 queries: {
23 queryFn: defaultQueryFn,
24 },
25 },
26 })
27​
28bootstrapApplication(MyAppComponent, {
29 providers: [provideTanStackQuery(createQueryClient)],
30})
31​
32export class PostsComponent {
33 // All you have to do now is pass a key!
34 readonly postsQuery = injectQuery<Array<Post>>(() => ({
35 queryKey: ['/posts'],
36 }))
37 // ...
39​
40export class PostComponent {
41 // You can even leave out the queryFn and just go straight into options
42 readonly postQuery = injectQuery<Post>(() => ({
43 enabled: this.postIdSignal() > 0,
44 queryKey: [`/posts/${this.postIdSignal()}`],
45 }))
46 // ...
48```
49​
50[//]: # 'Example'