Open History to see the last commit
1import { useInfiniteQuery } from '@tanstack/preact-query'
2import { productsQueries } from './services/products/queries'
3β
4type Product = {
5 name: string
6 shortDescription: string
7 salePrice: number
8}
9β
10type SearchResultsProps = {
11 query: string
12}
13β
14export default function SearchResults({ query = '' }: SearchResultsProps) {
15 const {
16 data: hits,
17 error,
18 isLoading,
19 isFetching,
20 status,
21 hasNextPage,
22 isFetchingNextPage,
23 fetchNextPage,
24 } = useInfiniteQuery({
25 ...productsQueries.search<Product>({
26 indexName: 'bestbuy',
27 query,
28 hitsPerPage: 5,
29 }),
30 select: (data) => data.pages.flatMap((page) => page.hits),
31 staleTime: 30 * 1000, // 30s
32 gcTime: 15 * 60 * 1000, // 15m
33 })
34β
35 if (!query) return null
36β
37 if (isLoading) return <div className="loading">Loading...</div>
38β
39 if (status === 'error') return <div>Error: {error.message}</div>
40β
41 return (
42 <div>
43 <div className="search-status">
44 Status: {status} {isFetching && <span>fetching...</span>}
45 </div>
46 <div>
47 <div className="search-result">
48 {hits && hits.length > 0 ? (
49 hits.map((product) => (
50 <li key={product.objectID} className="product">
51 <span className="product-name">{product.name}</span>
52 {product.shortDescription && (
53 <>
54 <br />
55 <span className="product-description">
56 {product.shortDescription}
57 </span>
58 </>
59 )}
60 <br />
61 <span className="product-price">${product.salePrice}</span>
62 </li>
63 ))
64 ) : (
65 <h3>No products found!</h3>
66 )}
67 </div>
68 {hasNextPage && (
69 <button
70 type="button"
71 className="search-more"
72 onClick={() => fetchNextPage()}
73 disabled={isFetching}
74 >
75 more
76 </button>
77 )}
78 {isFetchingNextPage && (
79 <div className="search-status">Fetching next page...</div>
80 )}
81 </div>
82 </div>
83 )
84}