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

FavoriteButton.vue

33 lines980 Bytes

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