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

SearchResults.svelte

76 lines2.1 KB

1<script lang="ts">
2 import { createInfiniteQuery } from '@tanstack/svelte-query'
3 import { productsQueries } from './services/products/queries'
4​
5 type Product = {
6 name: string
7 shortDescription: string
8 salePrice: number
9 }
10​
11 type Props = {
12 query: string
13 }
14​
15 let { query = '' }: Props = $props()
16​
17 const searchQuery = createInfiniteQuery(() => ({
18 ...productsQueries.search<Product>({
19 indexName: 'bestbuy',
20 query,
21 hitsPerPage: 5,
22 }),
23 select: (data) => data.pages.flatMap((page) => page.hits),
24 staleTime: 30 * 1000, // 30s
25 gcTime: 15 * 60 * 1000, // 15m
26 }))
27</script>
28​
29{#if query}
30 {#if searchQuery.isLoading}
31 <div class="loading">Loading...</div>
32 {:else if searchQuery.status === 'error'}
33 <div>Error: {searchQuery.error.message}</div>
34 {:else}
35 <div>
36 <div class="search-status">
37 Status: {searchQuery.status}
38 {#if searchQuery.isFetching}<span>fetching...</span>{/if}
39 </div>
40 <div>
41 <div class="search-result">
42 {#if searchQuery.data && searchQuery.data.length > 0}
43 {#each searchQuery.data as product (product.objectID)}
44 <li class="product">
45 <span class="product-name">{product.name}</span>
46 {#if product.shortDescription}
47 <br />
48 <span class="product-description">
49 {product.shortDescription}
50 </span>
51 {/if}
52 <br />
53 <span class="product-price">${product.salePrice}</span>
54 </li>
55 {/each}
56 {:else}
57 <h3>No products found!</h3>
58 {/if}
59 </div>
60 {#if searchQuery.hasNextPage}
61 <button
62 type="button"
63 class="search-more"
64 onclick={() => searchQuery.fetchNextPage()}
65 disabled={searchQuery.isFetching}
66 >
67 more
68 </button>
69 {/if}
70 {#if searchQuery.isFetchingNextPage}
71 <div class="search-status">Fetching next page...</div>
72 {/if}
73 </div>
74 </div>
75 {/if}
76{/if}