create form component
unknown
typescript
2 years ago
2.8 kB
7
Indexable
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { ChangeEvent } from "react";
async function createBlog(formData: BlogForm) {
try {
await fetch("http://localhost:3001/api/blogs/", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(formData),
});
} catch (err) {
console.log("Error occured");
}
}
type Props = {};
function CreateForm({}: Props) {
const router = useRouter();
const [formData, setFormData] = useState<BlogForm>({
title: "",
tags: "",
content: "",
isPublish: "on",
});
const [createStatus, setCreateStatus] = useState("Create Blog");
const handleChange = (
e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
const { name, value, type } = e.target;
const newValue =
type === "checkbox" ? (e.target as HTMLInputElement).checked : value;
setFormData({
...formData,
[name]: newValue,
});
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); // Prevent the default form submission
try {
setCreateStatus("Creating...");
await createBlog(formData);
setCreateStatus("Create Blog");
router.push("/blog");
// Handle successful blog creation, e.g., redirect to a new page
} catch (error) {
// Handle errors, e.g., display an error message
}
};
return (
<form onSubmit={handleSubmit}>
<input
required
className="border border-black mx-1"
placeholder="Title"
name="title"
type="text"
value={formData.title}
onChange={handleChange}
/>
<input
required
className="border border-black mx-1"
placeholder="Tags Separated by space "
name="tags"
type="text"
value={formData.tags}
onChange={handleChange}
/>
<textarea
required
className="border border-black mx-1"
placeholder="Content"
name="content"
value={formData.content}
onChange={handleChange}
/>
<input type="file" accept="image/*" name="img" />
<input
type="checkbox"
name="isPublish"
id="isPublish"
checked
value={formData.isPublish}
onChange={handleChange}
/>
<label htmlFor="isPublish">Publish</label>
<button
className="border border-black p-1"
disabled={createStatus === "Create Blog" ? false : true}
>
{createStatus}
</button>
</form>
);
}
export default CreateForm;
Editor is loading...