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

post-detail.ts

53 lines1.4 KB

1import { createQueryController } from '@tanstack/lit-query'
2import { LitElement, html } from 'lit'
3import type { Post } from './types'
4​
5class PostDetail extends LitElement {
6 static properties = {
7 postId: { attribute: false },
8 }
9​
10 postId = -1
11​
12 // You can even leave out the queryFn and just go straight into options
13 private readonly post = createQueryController<Post>(this, () => ({
14 queryKey: [`/posts/${this.postId}`],
15 enabled: !!this.postId,
16 }))
17​
18 protected override createRenderRoot(): HTMLElement | DocumentFragment {
19 return this
20 }
21​
22 private back(event: Event) {
23 event.preventDefault()
24 this.dispatchEvent(new CustomEvent('set-post-id', { detail: -1 }))
25 }
26​
27 render() {
28 const { isPending, isError, isFetching, data, error } = this.post()
29​
30 return html`
31 <div>
32 <div>
33 <a href="#posts" @click=${this.back}>Back</a>
34 </div>
35 ${
36 !this.postId || isPending
37 ? html`<div>Loading...</div>`
38 : isError
39 ? html`<span>Error: ${error.message}</span>`
40 : html`
41 <h1>${data.title}</h1>
42 <div>
43 <p>${data.body}</p>
44 </div>
45 <div>${isFetching ? 'Background Updating...' : ' '}</div>
46 `
47 }
48 </div>
49 `
50 }
52​
53customElements.define('post-detail', PostDetail)