fix(examples/vue/basic): share the post queries with 'queryOptions' i… · TanStack/query@71fb763 · GitHub
Skip to content

Commit 71fb763

Browse files
authored
fix(examples/vue/basic): share the post queries with 'queryOptions' in 'src/api.ts' and mark visited posts from the query cache (#12161)
1 parent ca7af33 commit 71fb763

4 files changed

Lines changed: 43 additions & 33 deletions

File tree

‎examples/vue/basic/src/App.vue‎

Lines changed: 1 addition & 5 deletions

‎examples/vue/basic/src/Post.vue‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,13 @@
11
<script setup lang="ts">
22
import { useQuery } from '@tanstack/vue-query'
3-
4-
import type { Post } from './types'
3+
import { postQueryOptions } from './api'
54
65
const props = defineProps<{ postId: number }>()
76
defineEmits<{ setPostId: [id: number] }>()
87
9-
const fetcher = async (id: number): Promise<Post> => {
10-
const response = await fetch(
11-
`https://jsonplaceholder.typicode.com/posts/${id}`,
12-
)
13-
if (!response.ok) throw new Error('Failed to fetch post')
14-
return await response.json()
15-
}
16-
17-
const { isPending, isError, isFetching, data, error } = useQuery({
18-
queryKey: ['post', () => props.postId],
19-
queryFn: () => fetcher(props.postId),
20-
})
8+
const { isPending, isError, isFetching, data, error } = useQuery(() =>
9+
postQueryOptions(props.postId),
10+
)
2111
</script>
2212

2313
<template>

‎examples/vue/basic/src/Posts.vue‎

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,13 @@
11
<script setup lang="ts">
2-
import { useQuery } from '@tanstack/vue-query'
2+
import { useQuery, useQueryClient } from '@tanstack/vue-query'
3+
import { postQueryOptions, postsQueryOptions } from './api'
34
4-
import type { Post } from './types'
5-
6-
defineProps<{ isVisited: (id: number) => boolean }>()
75
defineEmits<{ setPostId: [id: number] }>()
86
9-
const fetcher = async (): Promise<Array<Post>> => {
10-
const response = await fetch('https://jsonplaceholder.typicode.com/posts')
11-
if (!response.ok) throw new Error('Failed to fetch posts')
12-
return await response.json()
13-
}
7+
const queryClient = useQueryClient()
148
15-
const { isPending, isError, isFetching, data, error } = useQuery({
16-
queryKey: ['posts'],
17-
queryFn: fetcher,
18-
})
9+
const { isPending, isError, isFetching, data, error } =
10+
useQuery(postsQueryOptions())
1911
</script>
2012

2113
<template>
@@ -28,7 +20,11 @@ const { isPending, isError, isFetching, data, error } = useQuery({
2820
<a
2921
@click="$emit('setPostId', item.id)"
3022
href="#"
31-
:class="{ visited: isVisited(item.id) }"
23+
:class="{
24+
visited: queryClient.getQueryData(
25+
postQueryOptions(item.id).queryKey,
26+
),
27+
}"
3228
>{{ item.title }}</a
3329
>
3430
</li>

‎examples/vue/basic/src/api.ts‎

Lines changed: 28 additions & 0 deletions

0 commit comments

Comments
 (0)