1import { useContext, useState } from "react";
2import { useParams, useNavigate } from "react-router";
3
4import PageTitle from "@/components/page-title";
5import GoBack from "@/components/goback";
6import ActivityForm from "@/components/activity-form";
7
8import { AppContext } from "@/ContextProvider";
9
10const ActivityEdit = () => {
11 const params = useParams();
12 const navigate = useNavigate();
13 const [enableDelete, setEnableDelete] = useState(false);
14
15 const { state, dispatch } = useContext(AppContext);
16
17 const { friends } = state;
18 const activity = state.activities.find((a) => a.id === params.id);
19 const activityTitle = activity?.title || "";
20
21 if (!activity) {
22 return (
23 <>
24 <GoBack />
25 <PageTitle title="activity not found" />
26
27 <h1>activity not found</h1>
28 </>
29 );
30 }
31
32 function handleSubmit(newActivity) {
33 dispatch({
34 type: "updateActivity",
35 payload: { id: params.id, newActivity },
36 });
37 navigate("/activities");
38 }
39
40 function handleDelete() {
41 dispatch({
42 type: "deleteActivity",
43 payload: { id: params.id },
44 });
45 navigate("/activities");
46 }
47
48 return (
49 <>
50 <GoBack />
51 <PageTitle title={`edit ${activityTitle}`} />
52
53 <h1 className="h6">
54 <span className="muted small">edit</span> {activityTitle}
55 </h1>
56
57 <ActivityForm
58 friends={friends}
59 onSubmit={handleSubmit}
60 formInfo={{
61 type: "edit",
62 defaultValues: activity,
63 }}
64 />
65
66 <div className="info-box info-box-danger" style={{ marginTop: "30px" }}>
67 <h5 style={{ border: "0px", margin: "0px", fontWeight: "bold" }}>
68 Delete this activity?
69 </h5>
70 <label>
71 <input
72 type="checkbox"
73 checked={enableDelete}
74 onChange={(e) => {
75 setEnableDelete(e.target.checked);
76 }}
77 />
78 I want to delete <strong>{activityTitle}</strong>
79 </label>
80
81 <div>
82 <button
83 className="btn btn-danger"
84 disabled={!enableDelete}
85 onClick={handleDelete}
86 >
87 delete
88 </button>
89 </div>
90 </div>
91 </>
92 );
93};
94
95export default ActivityEdit;