-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.jsx
80 lines (67 loc) · 1.61 KB
/
page.jsx
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
"use client";
import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Form from "@components/Form";
const UpdatePromptPage = () => {
return (
<Suspense fallback={<><p>Loading...</p></>}>
<UpdatePrompt />
</Suspense>
);
};
export default UpdatePromptPage;
const UpdatePrompt = () => {
const router = useRouter();
const searchParams = useSearchParams();
const promptId = searchParams.get("id");
const [submitting, setSubmitting] = useState(false);
const [post, setPost] = useState({
prompt: "",
tag: "",
});
useEffect(() => {
const getPromptDetails = async () => {
const response = await fetch(`/api/prompt/${promptId}`);
const data = await response.json();
setPost({
prompt: data.prompt,
tag: data.tag,
});
};
if (promptId) {
getPromptDetails();
}
}, [promptId]);
const updatePrompt = async (event) => {
event.preventDefault();
setSubmitting(true);
if (!promptId) {
return alert("Prompt ID not found.");
}
try {
const response = await fetch(`/api/prompt/${promptId}`, {
method: "PATCH",
body: JSON.stringify({
prompt: post.prompt,
tag: post.tag,
}),
});
if (response.ok) {
router.push("/");
}
} catch (error) {
console.log(error);
} finally {
setSubmitting(false);
}
};
return (
<Form
type="Edit"
post={post}
setPost={setPost}
submitting={submitting}
handleSubmit={updatePrompt}
/>
);
};