Open History to see the last commit
1import { createQueryController, useQueryClient } from '@tanstack/lit-query'
2import { LitElement, html } from 'lit'
3import { styleMap } from 'lit/directives/style-map.js'
4import type { Post } from './types'
5β
6class PostList extends LitElement {
7 // All you have to do now is pass a key!
8 private readonly posts = createQueryController<Array<Post>>(this, {
9 queryKey: ['/posts'],
10 })
11β
12 protected override createRenderRoot(): HTMLElement | DocumentFragment {
13 return this
14 }
15β
16 private setPostId(id: number) {
17 this.dispatchEvent(new CustomEvent('set-post-id', { detail: id }))
18 }
19β
20 render() {
21 const queryClient = useQueryClient()
22 const { isPending, isError, isFetching, data, error } = this.posts()
23β
24 return html`
25 <div>
26 <h1>Posts</h1>
27 <div>
28 ${
29 isPending
30 ? html`<div>Loading...</div>`
31 : isError
32 ? html`<span>Error: ${error.message}</span>`
33 : html`
34 <div>
35 ${data.map(
36 (post) => html`
37 <p>
38 <a
39 href="#${post.id}"
40 style=${styleMap(
41 queryClient.getQueryData([`/posts/${post.id}`])
42 ? { fontWeight: 'bold', color: 'green' }
43 : {},
44 )}
45 @click=${(event: Event) => {
46 event.preventDefault()
47 this.setPostId(post.id)
48 }}
49 >
50 ${post.title}
51 </a>
52 </p>
53 `,
54 )}
55 </div>
56 <div>${isFetching ? 'Background Updating...' : ' '}</div>
57 `
58 }
59 </div>
60 </div>
61 `
62 }
63}
64β
65customElements.define('post-list', PostList)