Open History to see the last commit
1---
2id: query-functions
3title: Query Functions
4---
5β
6A query function can be any function that returns a promise. The promise should resolve data or throw an error.
7β
8```ts
9createQueryController(this, {
10 queryKey: ['todos'],
11 queryFn: fetchTodos,
12})
13β
14createQueryController(this, () => ({
15 queryKey: ['todo', this.todoId],
16 queryFn: () => fetchTodo(this.todoId),
17}))
18```
19β
20## Handling Errors
21β
22TanStack Query needs failed query functions to throw or return a rejected promise. Some clients do that automatically. The browser `fetch` API does not, so check `response.ok` yourself:
23β
24```ts
25async function fetchTodos(): Promise<Todo[]> {
26 const response = await fetch('/api/todos')
27β
28 if (!response.ok) {
29 throw new Error('Failed to fetch todos')
30 }
31β
32 return response.json() as Promise<Todo[]>
33}
34```
35β
36The thrown error is available on the query result:
37β
38```ts
39const query = this.todos()
40β
41if (query.isError) {
42 return html`Error: ${query.error.message}`
43}
44```
45β
46## Query Function Context
47β
48TanStack Query passes a context object to every query function. It includes:
49β
50- `queryKey`: the current query key
51- `client`: the `QueryClient`
52- `signal`: an `AbortSignal` for cancellation
53- `meta`: optional query metadata
54β
55```ts
56createQueryController(this, {
57 queryKey: ['todos', { status: 'open' }],
58 queryFn: async ({ queryKey, signal }) => {
59 const [, filters] = queryKey
60 const response = await fetch(`/api/todos?status=${filters.status}`, {
61 signal,
62 })
63 if (!response.ok) throw new Error('Failed to fetch todos')
64 return response.json() as Promise<Todo[]>
65 },
66})
67```
68β
69Infinite query functions also receive `pageParam`:
70β
71```ts
72createInfiniteQueryController(this, {
73 queryKey: ['projects'],
74 queryFn: ({ pageParam }) => fetchProjectsPage(pageParam),
75 initialPageParam: 1,
76 getNextPageParam: (lastPage) =>
77 lastPage.hasMore ? lastPage.page + 1 : undefined,
78})
79```
80β
81See [Infinite Queries](./infinite-queries.md) for the controller-specific behavior.