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

quick-start.md

83 lines2.1 KB

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 }
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 }
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).