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

character-view.ts

57 lines1.5 KB

1import { LitElement, html } from 'lit'
2import { createQueryController } from '@tanstack/lit-query'
3import { charactersQueries } from './services/characters/queries'
4​
5class CharacterView extends LitElement {
6 static properties = {
7 characterId: { attribute: false },
8 }
9​
10 characterId = ''
11​
12 private readonly character = createQueryController(this, () =>
13 charactersQueries.detail(
14 this.isValidId ? Number(this.characterId) : undefined,
15 ),
16 )
17​
18 protected override createRenderRoot(): HTMLElement | DocumentFragment {
19 return this
20 }
21​
22 private get isValidId() {
23 return /^\d+$/.test(this.characterId) && Number(this.characterId) > 0
24 }
25​
26 private renderCharacter() {
27 const { status, data, error, isFetching } = this.character()
28​
29 if (!this.isValidId) return 'Invalid character ID'
30 if (status === 'pending') return 'Loading...'
31 if (status === 'error') return html`<span>Error: ${error.message}</span>`
32​
33 return html`
34 <h1>${data.name}</h1>
35 <div>
36 <p>status: ${data.status}</p>
37 <p>species: ${data.species}</p>
38 <p>gender: ${data.gender}</p>
39 <p>origin: ${data.origin.name}</p>
40 </div>
41 <div>${isFetching ? 'Background Updating...' : ' '}</div>
42 `
43 }
44​
45 render() {
46 return html`
47 <div style="text-align: center">
48 ${this.renderCharacter()}
49 <br />
50 <br />
51 <a href="/">Back</a>
52 </div>
53 `
54 }
56​
57customElements.define('character-view', CharacterView)