Open History to see the last commit
1import { Form, redirect, useLoaderData, useNavigate } from 'react-router-dom'
2import { useSuspenseQuery } from '@tanstack/react-query'
3import { updateContact } from '../contacts'
4import { contactDetailQuery } from './contact'
5import type { ActionFunctionArgs } from 'react-router-dom'
6import type { Contact } from '../contacts'
7import type { QueryClient } from '@tanstack/react-query'
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 updateContact(params.contactId, updates)
19 queryClient.invalidateQueries({ queryKey: ['contacts'] })
20 return redirect(`/contacts/${params.contactId}`)
21 }
22β
23export default function Edit() {
24 const { contactId } = useLoaderData() as Awaited<
25 ReturnType<ReturnType<typeof loader>>
26 >
27 const { data: contact } = useSuspenseQuery(contactDetailQuery(contactId))
28β
29 return <ContactForm contact={contact} />
30}
31β
32export function ContactForm({ contact }: { contact?: Contact }) {
33 const navigate = useNavigate()
34β
35 return (
36 <Form method="post" id="contact-form">
37 <p>
38 <span>Name</span>
39 <input
40 placeholder="First"
41 aria-label="First name"
42 type="text"
43 name="first"
44 defaultValue={contact?.first}
45 />
46 <input
47 placeholder="Last"
48 aria-label="Last name"
49 type="text"
50 name="last"
51 defaultValue={contact?.last}
52 />
53 </p>
54 <label>
55 <span>Twitter</span>
56 <input
57 type="text"
58 name="twitter"
59 placeholder="@jack"
60 defaultValue={contact?.twitter}
61 />
62 </label>
63 <label>
64 <span>Avatar URL</span>
65 <input
66 placeholder="https://example.com/avatar.jpg"
67 type="text"
68 name="avatar"
69 defaultValue={contact?.avatar}
70 />
71 </label>
72 <label>
73 <span>Notes</span>
74 <textarea name="notes" defaultValue={contact?.notes} rows={6} />
75 </label>
76 <p>
77 <button type="submit">Save</button>
78 <button
79 type="button"
80 onClick={() => {
81 navigate(-1)
82 }}
83 >
84 Cancel
85 </button>
86 </p>
87 </Form>
88 )
89}