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

app.vue

64 lines2.1 KB

1<script setup lang="ts">
2import { ref, watchEffect } from 'vue'
3import {
4 keepPreviousData,
5 noop,
6 useQuery,
7 useQueryClient,
8} from '@tanstack/vue-query'
9import { VueQueryDevtools } from '@tanstack/vue-query-devtools'
10import { projectsQueries } from './services/projects/queries'
11​
12const queryClient = useQueryClient()
13const page = ref(0)
14​
15const { status, data, error, isFetching, isPlaceholderData } = useQuery(() => ({
16 ...projectsQueries.list(page.value),
17 placeholderData: keepPreviousData,
18}))
19​
20// Prefetch the next page!
21watchEffect(() => {
22 if (!isPlaceholderData.value && data.value?.hasMore) {
23 queryClient.query(projectsQueries.list(page.value + 1)).catch(noop)
24 }
25})
26</script>
27​
28<template>
29 <div>
30 <p>
31 In this example, each page of data remains visible as the next page is
32 fetched. The buttons and capability to proceed to the next page are also
33 suppressed until the next page cursor is known. Each page is cached as a
34 normal query too, so when going to previous pages, you'll see them
35 instantaneously while they are also refetched invisibly in the background.
36 </p>
37 <div v-if="status === 'pending'">Loading...</div>
38 <div v-else-if="status === 'error'">Error: {{ error?.message }}</div>
39 <!-- `data` will either resolve to the latest page's data -->
40 <!-- or if fetching a new page, the last successful page's data -->
41 <div v-else>
42 <p v-for="project in data?.projects" :key="project.id">
43 {{ project.name }}
44 </p>
45 </div>
46 <div>Current Page: {{ page + 1 }}</div>
47 <button :disabled="page === 0" @click="page = Math.max(page - 1, 0)">
48 Previous Page
49 </button>
50 {{ ' ' }}
51 <button
52 :disabled="isPlaceholderData || !data?.hasMore"
53 @click="page = data?.hasMore ? page + 1 : page"
54 >
55 Next Page
56 </button>
57 <!-- Since the last page's data potentially sticks around between page requests, -->
58 <!-- we can use `isFetching` to show a background loading -->
59 <!-- indicator since our `status === 'pending'` state won't be triggered -->
60 <span v-if="isFetching"> Loading...</span>
61 {{ ' ' }}
62 <VueQueryDevtools initial-is-open />
63 </div>
64</template>