-
Yusuf Akgül authoredYusuf Akgül authored
post-messages.tsx 1.96 KiB
"use client"
import { Message, Prisma } from "@prisma/client";
import { useRouter } from "next/navigation";
import { startTransition, useState } from "react";
type messageType = Prisma.MessageUncheckedCreateInput
export default function PostMessageForm(props: { data: Message[] | null }) {
const [formData, setFormData] = useState<messageType>({ content: "" } as messageType);
// const [messagesState, setMessages] = useState(props.data)
const router = useRouter();
async function postMessage(e: any) {
e.preventDefault()
// setMessages([...messagesState, formData])
console.log(formData)
formData.author = "Default Author"
const response = await fetch('http://localhost:3000/api/messages', {
method: 'POST',
body: JSON.stringify(formData)
})
startTransition(() => {
// Refresh the current route and fetch new data from the server without
// losing client-side browser or React state.
router.refresh();
});
return await response.json()
}
const characterCount = formData.content.length;
const isOverLimit = characterCount > 1000;
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const { value } = e.target;
setFormData({ content: value });
};
return (
<div>
<form onSubmit={postMessage}>
<textarea
placeholder="Write something..."
name="content"
value={formData.content}
onChange={handleInputChange}
className="w-full p-2 border border-gray-600 rounded-xl resize-none"
rows={5}
maxLength={1000}
></textarea>
<div className="flex justify-end mt-2">
<span className={`${isOverLimit ? "text-red-500" : "text-gray-500"} text-sm`}>
{characterCount}/{1000}
</span>
</div>
<button type="submit" className="mt-2 bg-gray-300 text-gray-800 px-4 py-2 rounded float-right">
Post
</button>
</form>
</div>
)
}