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

FavoriteButton.vue

37 lines975 Bytes

1<script setup lang="ts">
2import { computed } from 'vue'
3import { useMutation, useQueryClient } from '@tanstack/vue-query'
4import { contactsMutations, contactsQueries } from './services/contacts/queries'
5import type { Contact } from './services/contacts/types'
6​
7const props = defineProps<{ contact: Contact }>()
8​
9const queryClient = useQueryClient()
10​
11const { mutate, variables, isPending } = useMutation({
12 ...contactsMutations.update(),
13 onSettled: () =>
14 queryClient.invalidateQueries({ queryKey: contactsQueries.all() }),
15})
16​
17const favorite = computed(() =>
18 isPending.value
19 ? Boolean(variables.value?.updates.favorite)
20 : props.contact.favorite,
22</script>
23​
24<template>
25 <form
26 @submit.prevent="
27 mutate({ id: contact.id, updates: { favorite: !favorite } })
28 "
29 >
30 <button
31 type="submit"
32 :title="favorite ? 'Remove from favorites' : 'Add to favorites'"
33 >
34 {{ favorite ? 'β˜…' : 'β˜†' }}
35 </button>
36 </form>
37</template>