Open History to see the last commit
1import * as React from "react";
2import { Form, useFetcher, useParams } from "react-router-dom";
3import { getContact, updateContact } from "../contacts";
4import { useQuery } from "@tanstack/react-query";
5β
6const contactDetailQuery = (id) => ({
7 queryKey: ["contacts", "detail", id],
8 queryFn: async () => {
9 const contact = await getContact(id);
10 if (!contact) {
11 throw new Response("", {
12 status: 404,
13 statusText: "Not Found",
14 });
15 }
16 return contact;
17 },
18});
19β
20export const loader =
21 (queryClient) =>
22 async ({ params }) => {
23 const query = contactDetailQuery(params.contactId);
24 return (
25 queryClient.getQueryData(query.queryKey) ??
26 (await queryClient.fetchQuery(query))
27 );
28 };
29β
30export const action =
31 (queryClient) =>
32 async ({ request, params }) => {
33 let formData = await request.formData();
34 const contact = await updateContact(params.contactId, {
35 favorite: formData.get("favorite") === "true",
36 });
37 await queryClient.invalidateQueries({ queryKey: ["contacts"] });
38 return contact;
39 };
40β
41export default function Contact() {
42 const params = useParams();
43 const { data: contact } = useQuery(contactDetailQuery(params.contactId));
44β
45 return (
46 <div id="contact">
47 <div>
48 <img key={contact.avatar} src={contact.avatar || null} />
49 </div>
50β
51 <div>
52 <h1>
53 {contact.first || contact.last ? (
54 <>
55 {contact.first} {contact.last}
56 </>
57 ) : (
58 <i>No Name</i>
59 )}{" "}
60 <Favorite contact={contact} />
61 </h1>
62β
63 {contact.twitter && (
64 <p>
65 <a target="_blank" href={`https://twitter.com/${contact.twitter}`}>
66 {contact.twitter}
67 </a>
68 </p>
69 )}
70β
71 {contact.notes && <p>{contact.notes}</p>}
72β
73 <div>
74 <Form action="edit">
75 <button type="submit">Edit</button>
76 </Form>
77 <Form
78 method="post"
79 action="destroy"
80 onSubmit={(event) => {
81 // eslint-disable-next-line no-restricted-globals
82 if (!confirm("Please confirm you want to delete this record.")) {
83 event.preventDefault();
84 }
85 }}
86 >
87 <button type="submit">Delete</button>
88 </Form>
89 </div>
90 </div>
91 </div>
92 );
93}
94β
95function Favorite({ contact }) {
96 const fetcher = useFetcher();
97 let favorite = contact.favorite;
98 if (fetcher.formData) {
99 favorite = fetcher.formData.get("favorite") === "true";
100 }
101β
102 return (
103 <fetcher.Form method="post">
104 <button
105 name="favorite"
106 value={favorite ? "false" : "true"}
107 aria-label={favorite ? "Remove from favorites" : "Add to favorites"}
108 >
109 {favorite ? "β
" : "β"}
110 </button>
111 </fetcher.Form>
112 );
113}