Skip to content

Commit 5a85bb4

Browse files
committed
feat: implement user selection and posts fetching in playground
1 parent 0fadcfc commit 5a85bb4

File tree

2 files changed

+59
-15
lines changed

2 files changed

+59
-15
lines changed

playground/app/app.vue

Lines changed: 59 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,79 @@
11
<script setup>
2-
const getPosts = async () => {
2+
const selectedUser = ref(null)
3+
4+
const getUsers = async () => {
35
await new Promise(resolve => setTimeout(resolve, 2000))
4-
return await $fetch('https://jsonplaceholder.typicode.com/posts')
6+
return await $fetch('https://jsonplaceholder.typicode.com/users')
7+
}
8+
9+
const getPosts = async (userId) => {
10+
const url = 'https://jsonplaceholder.typicode.com/posts'
11+
return await $fetch(url, { method: 'GET', params: { userId } })
512
}
613
7-
const { isPending, isFetching, isError, data, error } = useQuery({
8-
queryKey: ['posts'],
9-
queryFn: getPosts,
10-
// staleTime: 1000 * 6,
14+
const { isPending: isUsersPending, data: users } = useQuery({
15+
queryKey: ['users'],
16+
queryFn: getUsers,
17+
})
18+
19+
const selectedUserId = computed(() => selectedUser.value?.id)
20+
21+
const { isPending, isFetching, isError, data: posts, error } = useQuery({
22+
queryKey: ['posts', selectedUserId],
23+
queryFn: () => getPosts(selectedUserId.value),
24+
staleTime: 1000 * 10,
25+
gcTime: 1000 * 20,
26+
enabled: !selectedUser.value,
27+
1128
})
29+
function selectUser(user) {
30+
selectedUser.value = user
31+
}
1232
</script>
1333
1434
<template>
35+
<div>
36+
<h1>Users</h1>
37+
<div v-if="isUsersPending">
38+
Loading...
39+
</div>
40+
<div
41+
v-else
42+
:style="{
43+
display: 'grid',
44+
gap: '0.5rem',
45+
paddingLeft: '0.5rem',
46+
}"
47+
>
48+
<div
49+
v-for="user in users"
50+
:key="user.id"
51+
:style="{
52+
cursor: 'pointer',
53+
backgroundColor: selectedUserId === user.id ? 'blue' : 'white',
54+
color: selectedUserId === user.id ? 'white' : 'black',
55+
padding: '0.25rem',
56+
}"
57+
@click="selectUser(user)"
58+
>
59+
{{ user.name }} ({{ user.email }})
60+
</div>
61+
</div>
62+
</div>
1563
<div>
1664
<h1>Posts</h1>
1765
<div v-if="isPending">
1866
Loading...
1967
</div>
20-
21-
<div v-else-if="isError">
22-
{{ error.message }}
23-
</div>
24-
2568
<div v-else-if="isFetching">
26-
Refetching...
69+
Fetching...
2770
</div>
28-
71+
<ul v-else-if="isError">
72+
<li>Error: {{ error.message }}</li>
73+
</ul>
2974
<ul v-else>
3075
<li
31-
v-for="post in data"
76+
v-for="post in posts"
3277
:key="post.id"
3378
>
3479
{{ post.title }}

playground/nuxt.config.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ export default defineNuxtConfig({
1313
defaultOptions: {
1414
queries: {
1515
refetchOnWindowFocus: false,
16-
refetchInterval: 5000,
1716
},
1817
},
1918
},

0 commit comments

Comments
 (0)