Open History to see the last commit
1import { useSuspenseQuery } from '@tanstack/react-query'
2import { Form, redirect, useLoaderData, useNavigate } from 'react-router'
3import { contactsAPI } from '../services/contacts/api'
4import { contactsQueries } from '../services/contacts/queries'
5import type { QueryClient } from '@tanstack/react-query'
6import type { ActionFunctionArgs } from 'react-router'
7import type { Contact } from '../services/contacts/types'
8import type { loader } from './contact'
9β
10export const action =
11 (queryClient: QueryClient) =>
12 async ({ request, params }: ActionFunctionArgs) => {
13 const formData = await request.formData()
14 const updates = Object.fromEntries(formData)
15 if (!params.contactId) {
16 throw new Error('No contact ID provided')
17 }
18 await contactsAPI.updateContact(params.contactId, updates)
19 queryClient.invalidateQueries({ queryKey: contactsQueries.all() })
20 return redirect(`/contacts/${params.contactId}`)
21 }
22β
23export default function Edit() {
24 const { contactId } = useLoaderData<ReturnType<typeof loader>>()
25 const { data: contact } = useSuspenseQuery(contactsQueries.detail(contactId))
26β
27 return <ContactForm contact={contact} />
28}
29β
30export function ContactForm({ contact }: { contact?: Contact }) {
31 const navigate = useNavigate()
32β
33 return (
34 <Form method="post" id="contact-form">
35 <p>
36 <span>Name</span>
37 <input
38 placeholder="First"
39 aria-label="First name"
40 type="text"
41 name="first"
42 defaultValue={contact?.first}
43 />
44 <input
45 placeholder="Last"
46 aria-label="Last name"
47 type="text"
48 name="last"
49 defaultValue={contact?.last}
50 />
51 </p>
52 <label>
53 <span>Twitter</span>
54 <input
55 type="text"
56 name="twitter"
57 placeholder="@jack"
58 defaultValue={contact?.twitter}
59 />
60 </label>
61 <label>
62 <span>Avatar URL</span>
63 <input
64 placeholder="https://example.com/avatar.jpg"
65 type="text"
66 name="avatar"
67 defaultValue={contact?.avatar}
68 />
69 </label>
70 <label>
71 <span>Notes</span>
72 <textarea name="notes" defaultValue={contact?.notes} rows={6} />
73 </label>
74 <p>
75 <button type="submit">Save</button>
76 <button
77 type="button"
78 onClick={() => {
79 navigate(-1)
80 }}
81 >
82 Cancel
83 </button>
84 </p>
85 </Form>
86 )
87}