Open History to see the last commit
1---
2id: quick-start
3title: Quick Start
4---
5β
6This snippet shows the three core Lit Query concepts:
7β
8- [Queries](./guides/queries.md)
9- [Mutations](./guides/mutations.md)
10- [Query Invalidation](./guides/query-invalidation.md)
11β
12For complete runnable examples, see [Basic](./examples/basic), [Pagination](./examples/pagination), and [SSR](./examples/ssr).
13β
14```ts
15import { LitElement, html } from 'lit'
16import {
17 QueryClient,
18 QueryClientProvider,
19 createMutationController,
20 createQueryController,
21} from '@tanstack/lit-query'
22import { addTodo, getTodos } from './api'
23β
24const queryClient = new QueryClient()
25β
26class AppQueryProvider extends QueryClientProvider {
27 constructor() {
28 super()
29 this.client = queryClient
30 }
31}
32β
33customElements.define('app-query-provider', AppQueryProvider)
34β
35class TodosView extends LitElement {
36 private readonly todos = createQueryController(this, {
37 queryKey: ['todos'],
38 queryFn: getTodos,
39 })
40β
41 private readonly createTodo = createMutationController(this, {
42 mutationFn: addTodo,
43 onSuccess: async () => {
44 await queryClient.invalidateQueries({ queryKey: ['todos'] })
45 },
46 })
47β
48 render() {
49 const query = this.todos()
50 const mutation = this.createTodo()
51β
52 if (query.isPending) return html`Loading...`
53 if (query.isError) return html`Error: ${query.error.message}`
54β
55 return html`
56 <ul>
57 ${query.data.map((todo) => html`<li>${todo.title}</li>`)}
58 </ul>
59β
60 <button
61 ?disabled=${mutation.isPending}
62 @click=${() => this.createTodo.mutate({ title: 'Write Lit docs' })}
63 >
64 Add Todo
65 </button>
66 `
67 }
68}
69β
70customElements.define('todos-view', TodosView)
71```
72β
73Mount the provider around your component:
74β
75```html
76<app-query-provider>
77 <todos-view></todos-view>
78</app-query-provider>
79```
80β
81The controllers are created with `this` because a `LitElement` is a `ReactiveControllerHost`. Lit Query uses the host lifecycle to subscribe, request updates, and clean up when the element disconnects.
82β
83Continue with [Reactive Controllers vs Hooks](./guides/reactive-controllers-vs-hooks.md) if you know React Query, or go straight to [Queries](./guides/queries.md).