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

SearchResults.tsx

80 lines1.9 KB

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