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