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

createQueryController.md

101 lines2.6 KB

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