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

PostList.vue

42 lines1.2 KB

1<script setup lang="ts">
2import { useQuery, useQueryClient } from '@tanstack/vue-query'
3import type { Post } from './types'
4​
5defineEmits<{ setPostId: [id: number] }>()
6​
7const queryClient = useQueryClient()
8​
9// All you have to do now is pass a key!
10const { isPending, isError, isFetching, data, error } = useQuery<Array<Post>>({
11 queryKey: ['/posts'],
12})
13</script>
14​
15<template>
16 <div>
17 <h1>Posts</h1>
18 <div>
19 <div v-if="isPending">Loading...</div>
20 <span v-else-if="isError">Error: {{ error?.message }}</span>
21 <template v-else-if="data">
22 <div>
23 <p v-for="post in data" :key="post.id">
24 <!-- We can use the queryCache here to show bold links for ones that are cached -->
25 <a
26 :href="`#${post.id}`"
27 :style="
28 queryClient.getQueryData([`/posts/${post.id}`])
29 ? { fontWeight: 'bold', color: 'green' }
30 : {}
31 "
32 @click.prevent="$emit('setPostId', post.id)"
33 >
34 {{ post.title }}
35 </a>
36 </p>
37 </div>
38 <div>{{ isFetching ? 'Background Updating...' : ' ' }}</div>
39 </template>
40 </div>
41 </div>
42</template>