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

createQueryController.md

97 lines2.3 KB

1---
2id: createQueryController
3title: createQueryController
4---
5​
6# Function: createQueryController()
7​
8```ts
9function createQueryController<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
10 host,
11 options,
12queryClient?): QueryResultAccessor<TData, TError>;
13```
14​
15Defined in: [packages/lit-query/src/createQueryController.ts:319](https://github.com/TanStack/query/blob/main/packages/lit-query/src/createQueryController.ts#L319)
16​
17Creates a Lit reactive controller that subscribes the host to a single query.
18​
19The returned accessor is callable and also exposes `current`, `refetch`,
20`suspense`, and `destroy`. When `options` is a function, it is re-read during
21host updates so query keys and options can follow reactive host state.
22​
23If `queryClient` is omitted, the controller resolves the client from the
24nearest connected `QueryClientProvider`.
25​
26## Type Parameters
27​
28### TQueryFnData
29​
30`TQueryFnData` = `unknown`
31​
32### TError
33​
34`TError` = `Error`
35​
36### TData
37​
38`TData` = `TQueryFnData`
39​
40### TQueryData
41​
42`TQueryData` = `TQueryFnData`
43​
44### TQueryKey
45​
46`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
47​
48## Parameters
49​
50### host
51​
52`ReactiveControllerHost`
53​
54The Lit reactive controller host that owns the query
55subscription.
56​
57### options
58​
59[`Accessor`](../type-aliases/Accessor.md)\<[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>\>
60​
61Query observer options, or a getter that returns options.
62​
63### queryClient?
64​
65`QueryClient`
66​
67Optional explicit query client. Provide this for
68controllers that should not resolve a client from Lit context.
69​
70## Returns
71​
72[`QueryResultAccessor`](../type-aliases/QueryResultAccessor.md)\<`TData`, `TError`\>
73​
74An accessor for the latest query result with query helper methods.
75​
76## Example
77​
78```ts
79import { LitElement, html } from 'lit'
80import { createQueryController } from '@tanstack/lit-query'
81​
82class TodosView extends LitElement {
83 private readonly todos = createQueryController(this, {
84 queryKey: ['todos'],
85 queryFn: async () => fetch('/api/todos').then((r) => r.json()),
86 })
87​
88 render() {
89 const query = this.todos()
90​
91 if (query.isPending) return html`Loading...`
92 if (query.isError) return html`Error`
93​
94 return html`<ul>${query.data.map((todo) => html`<li>${todo.title}</li>`)}</ul>`
95 }
97```