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

edit.tsx

99 lines2.6 KB

1import { action, redirect, useNavigate, useParams } from '@solidjs/router'
2import { useQuery } from '@tanstack/solid-query'
3import { Show } from 'solid-js'
4import { queryClient } from '../queryClient'
5import { contactsAPI } from '../services/contacts/api'
6import { contactsQueries } from '../services/contacts/queries'
7import type { Action } from '@solidjs/router'
8import type { Contact } from '../services/contacts/types'
9​
10export const editContact = action(
11 async (contactId: string, formData: FormData) => {
12 const updates = Object.fromEntries(formData)
13 await contactsAPI.updateContact(contactId, updates)
14 queryClient.invalidateQueries({ queryKey: contactsQueries.all() })
15 throw redirect(`/contacts/${contactId}`)
16 },
17 'editContact',
19​
20export default function Edit() {
21 const params = useParams<{ contactId: string }>()
22 const contactQuery = useQuery(() => ({
23 ...contactsQueries.detail(params.contactId),
24 throwOnError: true,
25 }))
26​
27 return (
28 <Show when={contactQuery.data}>
29 {(contact) => (
30 <ContactForm
31 action={editContact.with(contact().id)}
32 contact={contact()}
33 />
34 )}
35 </Show>
36 )
38​
39export function ContactForm(props: {
40 action: Action<[formData: FormData], never, unknown>
41 contact?: Contact
42}) {
43 const navigate = useNavigate()
44​
45 return (
46 <form method="post" action={props.action} id="contact-form">
47 <p>
48 <span>Name</span>
49 <input
50 placeholder="First"
51 aria-label="First name"
52 type="text"
53 name="first"
54 value={props.contact?.first ?? ''}
55 />
56 <input
57 placeholder="Last"
58 aria-label="Last name"
59 type="text"
60 name="last"
61 value={props.contact?.last ?? ''}
62 />
63 </p>
64 <label>
65 <span>Twitter</span>
66 <input
67 type="text"
68 name="twitter"
69 placeholder="@jack"
70 value={props.contact?.twitter ?? ''}
71 />
72 </label>
73 <label>
74 <span>Avatar URL</span>
75 <input
76 placeholder="https://example.com/avatar.jpg"
77 type="text"
78 name="avatar"
79 value={props.contact?.avatar ?? ''}
80 />
81 </label>
82 <label>
83 <span>Notes</span>
84 <textarea name="notes" value={props.contact?.notes ?? ''} rows={6} />
85 </label>
86 <p>
87 <button type="submit">Save</button>
88 <button
89 type="button"
90 onClick={() => {
91 navigate(-1)
92 }}
93 >
94 Cancel
95 </button>
96 </p>
97 </form>
98 )