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

default-query-function.md

49 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 queryClient = new QueryClient({
20 defaultOptions: {
21 queries: {
22 queryFn: defaultQueryFn,
23 },
24 },
25})
26​
27bootstrapApplication(MyAppComponent, {
28 providers: [provideTanStackQuery(queryClient)],
29})
30​
31export class PostsComponent {
32 // All you have to do now is pass a key!
33 readonly postsQuery = injectQuery<Array<Post>>(() => ({
34 queryKey: ['/posts'],
35 }))
36 // ...
38​
39export class PostComponent {
40 // You can even leave out the queryFn and just go straight into options
41 readonly postQuery = injectQuery<Post>(() => ({
42 enabled: this.postIdSignal() > 0,
43 queryKey: [`/posts/${this.postIdSignal()}`],
44 }))
45 // ...
47```
48​
49[//]: # 'Example'