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

SearchResults.vue

81 lines2.1 KB

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