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

post-list.ts

64 lines2.1 KB

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