|
| 1 | +<script setup lang="ts"> |
| 2 | +import { ref } from 'vue' |
| 3 | +import { useQuery, useQueryClient } from '@tanstack/vue-query' |
| 4 | +
|
| 5 | +type Post = { id: number; title: string; type: 'one' | 'two' } |
| 6 | +
|
| 7 | +const type = ref<'one' | 'two' | null>(null) |
| 8 | +
|
| 9 | +const { data } = useQuery<Post[]>({ |
| 10 | + queryKey: ['posts', () => String(type.value)], |
| 11 | + queryFn: () => { |
| 12 | + console.log('fetching posts', type.value) |
| 13 | + return fetch( |
| 14 | + `https://f4d556e10da84c26.mokky.dev/posts${ |
| 15 | + type.value ? `?type=${type.value}` : '' |
| 16 | + }` |
| 17 | + ).then((res) => res.json()) |
| 18 | + }, |
| 19 | +
|
| 20 | + staleTime: 4 * 60 * 1000, |
| 21 | + gcTime: Infinity, |
| 22 | +}) |
| 23 | +
|
| 24 | +const queryCache = useQueryClient() |
| 25 | +const patchRecord = async () => { |
| 26 | + if (!data.value) return |
| 27 | +
|
| 28 | + let type = 'one' |
| 29 | +
|
| 30 | + if (data.value[0].type === 'one') { |
| 31 | + type = 'two' |
| 32 | + } |
| 33 | +
|
| 34 | + const response = await fetch( |
| 35 | + `https://f4d556e10da84c26.mokky.dev/posts/${data.value[0].id}`, |
| 36 | + { |
| 37 | + method: 'PATCH', |
| 38 | + headers: { |
| 39 | + 'Content-Type': 'application/json', |
| 40 | + }, |
| 41 | + body: JSON.stringify({ type }), |
| 42 | + } |
| 43 | + ) |
| 44 | +
|
| 45 | + const patchedData = await response.json() |
| 46 | +
|
| 47 | + queryCache.invalidateQueries({ |
| 48 | + queryKey: ['posts'], |
| 49 | + // exact: true, |
| 50 | + // refetchType: 'all', |
| 51 | + }) |
| 52 | +} |
| 53 | +</script> |
| 54 | + |
| 55 | +<template> |
| 56 | + <div |
| 57 | + style=" |
| 58 | + display: flex; |
| 59 | + flex-direction: column; |
| 60 | + gap: 10px; |
| 61 | + margin-bottom: 10px; |
| 62 | + " |
| 63 | + > |
| 64 | + <select v-model="type"> |
| 65 | + <option :value="null">all</option> |
| 66 | + <option value="one">One</option> |
| 67 | + <option value="two">Two</option> |
| 68 | + </select> |
| 69 | + <div v-for="post in data" :key="post.id"> |
| 70 | + {{ post.title }} {{ post.type }} |
| 71 | + </div> |
| 72 | + </div> |
| 73 | + <button @click="patchRecord" style="margin-right: 20px">Patch</button> |
| 74 | +</template> |
0 commit comments