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

default-query-function.md

50 lines1.1 KB

// Define a default query function that will receive the query key
const defaultQueryFn: QueryFunction = async ({ queryKey }) => {
  const { data } = await axios.get(
    `https://jsonplaceholder.typicode.com${queryKey[0]}`,
  )
  return data
}

// provide the default query function to your app with defaultOptions
const createQueryClient = () =>
  new QueryClient({
    defaultOptions: {
      queries: {
        queryFn: defaultQueryFn,
      },
    },
  })

bootstrapApplication(MyAppComponent, {
  providers: [provideTanStackQuery(createQueryClient)],
})

export class PostsComponent {
  // All you have to do now is pass a key!
  readonly postsQuery = injectQuery<Array<Post>>(() => ({
    queryKey: ['/posts'],
  }))
  // ...
}

export class PostComponent {
  // You can even leave out the queryFn and just go straight into options
  readonly postQuery = injectQuery<Post>(() => ({
    enabled: this.postIdSignal() > 0,
    queryKey: [`/posts/${this.postIdSignal()}`],
  }))
  // ...
}