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

contacts.$contactId.index.tsx

115 lines2.9 KB

1import { Link, createFileRoute, useNavigate } from '@tanstack/react-router'
2import {
3 useMutation,
4 useQueryClient,
5 useSuspenseQuery,
6} from '@tanstack/react-query'
7import {
8 contactsMutations,
9 contactsQueries,
10} from '../services/contacts/queries'
11import type { Contact } from '../services/contacts/types'
12​
13export const Route = createFileRoute('/contacts/$contactId/')({
14 component: ContactPage,
15})
16​
17function ContactPage() {
18 const { contactId } = Route.useParams()
19 const { q } = Route.useSearch()
20 const { data: contact } = useSuspenseQuery(contactsQueries.detail(contactId))
21 const queryClient = useQueryClient()
22 const navigate = useNavigate()
23 const deleteContact = useMutation({
24 ...contactsMutations.delete(),
25 onSuccess: async () => {
26 await navigate({ to: '/', search: { q } })
27 await queryClient.invalidateQueries({ queryKey: contactsQueries.all() })
28 },
29 })
30​
31 return (
32 <div id="contact">
33 <div>
34 <img key={contact.avatar} src={contact.avatar || undefined} />
35 </div>
36​
37 <div>
38 <h1>
39 {contact.first || contact.last ? (
40 <>
41 {contact.first} {contact.last}
42 </>
43 ) : (
44 <i>No Name</i>
45 )}{' '}
46 <Favorite contact={contact} />
47 </h1>
48​
49 {contact.twitter && (
50 <p>
51 <a target="_blank" href={`https://twitter.com/${contact.twitter}`}>
52 {contact.twitter}
53 </a>
54 </p>
55 )}
56​
57 {contact.notes && <p>{contact.notes}</p>}
58​
59 <div>
60 <Link
61 to="/contacts/$contactId/edit"
62 params={{ contactId }}
63 search={{ q }}
64 className="button"
65 >
66 Edit
67 </Link>
68 <form
69 className="destroy"
70 onSubmit={(event) => {
71 event.preventDefault()
72 if (confirm('Please confirm you want to delete this record.')) {
73 deleteContact.mutate(contactId)
74 }
75 }}
76 >
77 <button type="submit">Delete</button>
78 </form>
79 </div>
80 </div>
81 </div>
82 )
84​
85function Favorite({ contact }: { contact: Contact }) {
86 const queryClient = useQueryClient()
87 const updateContact = useMutation({
88 ...contactsMutations.update(),
89 onSettled: () =>
90 queryClient.invalidateQueries({ queryKey: contactsQueries.all() }),
91 })
92 const favorite = updateContact.isPending
93 ? Boolean(updateContact.variables.updates.favorite)
94 : contact.favorite
95​
96 return (
97 <form
98 onSubmit={(event) => {
99 event.preventDefault()
100 updateContact.mutate({
101 id: contact.id,
102 updates: { favorite: !favorite },
103 })
104 }}
105 >
106 <button
107 name="favorite"
108 value={favorite ? 'false' : 'true'}
109 title={favorite ? 'Remove from favorites' : 'Add to favorites'}
110 >
111 {favorite ? 'β˜…' : 'β˜†'}
112 </button>
113 </form>
114 )