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

Post.vue

71 lines1.7 KB

1<script lang="ts">
2import { computed, defineComponent } from 'vue'
3import { useQuery } from '@tanstack/vue-query'
4​
5import { Author, Post } from './types'
6​
7const fetchPost = async (id: number): Promise<Post> =>
8 await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`).then(
9 (response) => response.json(),
10 )
11​
12const fetchAuthor = async (id: number): Promise<Author> =>
13 await fetch(`https://jsonplaceholder.typicode.com/users/${id}`).then(
14 (response) => response.json(),
15 )
16​
17export default defineComponent({
18 name: 'PostDetails',
19 props: {
20 postId: {
21 type: Number,
22 required: true,
23 },
24 },
25 emits: ['setPostId'],
26 setup(props) {
27 const {
28 isLoading,
29 isError,
30 isFetching,
31 data: post,
32 error,
33 } = useQuery(['post', props.postId], () => fetchPost(props.postId))
34​
35 const authorId = computed(() => post.value?.userId)
36​
37 const { data: author } = useQuery(
38 ['author', authorId],
39 () => fetchAuthor(authorId.value),
40 {
41 enabled: computed(() => !!post.value?.userId),
42 },
43 )
44​
45 return { isLoading, isError, isFetching, post, error, author }
46 },
47})
48</script>
49​
50<template>
51 <h1>Post {{ postId }}</h1>
52 <a @click="$emit('setPostId', -1)" href="#"> Back </a>
53 <div v-if="isLoading" class="update">Loading...</div>
54 <div v-else-if="isError">An error has occurred: {{ error }}</div>
55 <div v-else-if="post">
56 <h1>
57 {{ post.title }} <span v-if="author">by {{ author.name }}</span>
58 </h1>
59 <div>
60 <p>{{ post.body }}</p>
61 </div>
62 <div v-if="isFetching" class="update">Background Updating...</div>
63 </div>
64</template>
65​
66<style scoped>
67.update {
68 font-weight: bold;
69 color: green;
71</style>