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

search-results.ts

107 lines2.9 KB

1import { LitElement, html } from 'lit'
2import { createInfiniteQueryController } from '@tanstack/lit-query'
3import { productsQueries } from './services/products/queries'
4​
5type Product = {
6 name: string
7 shortDescription: string
8 salePrice: number
9}
10​
11class SearchResults extends LitElement {
12 static properties = {
13 query: { attribute: false },
14 }
15​
16 query = ''
17​
18 private readonly products = createInfiniteQueryController(this, () => ({
19 ...productsQueries.search<Product>({
20 indexName: 'bestbuy',
21 query: this.query,
22 hitsPerPage: 5,
23 }),
24 select: (data) => data.pages.flatMap((page) => page.hits),
25 staleTime: 30 * 1000, // 30s
26 gcTime: 15 * 60 * 1000, // 15m
27 }))
28​
29 protected override createRenderRoot(): HTMLElement | DocumentFragment {
30 return this
31 }
32​
33 render() {
34 if (!this.query) return null
35​
36 const {
37 isLoading,
38 status,
39 error,
40 isFetching,
41 data: products,
42 hasNextPage,
43 isFetchingNextPage,
44 } = this.products()
45​
46 if (isLoading) return html`<div class="loading">Loading...</div>`
47​
48 if (status === 'error') return html`<div>Error: ${error.message}</div>`
49​
50 return html`
51 <div>
52 <div class="search-status">
53 Status: ${status}
54 ${isFetching ? html`<span>fetching...</span>` : null}
55 </div>
56 <div>
57 <div class="search-result">
58 ${
59 products && products.length > 0
60 ? products.map(
61 (product) => html`
62 <li class="product">
63 <span class="product-name">${product.name}</span>
64 ${
65 product.shortDescription
66 ? html`
67 <br />
68 <span class="product-description">
69 ${product.shortDescription}
70 </span>
71 `
72 : null
73 }
74 <br />
75 <span class="product-price">$${product.salePrice}</span>
76 </li>
77 `,
78 )
79 : html`<h3>No products found!</h3>`
80 }
81 </div>
82 ${
83 hasNextPage
84 ? html`
85 <button
86 type="button"
87 class="search-more"
88 ?disabled=${isFetching}
89 @click=${() => this.products.fetchNextPage()}
90 >
91 more
92 </button>
93 `
94 : null
95 }
96 ${
97 isFetchingNextPage
98 ? html`<div class="search-status">Fetching next page...</div>`
99 : null
100 }
101 </div>
102 </div>
103 `
104 }
106​
107customElements.define('search-results', SearchResults)