diff --git a/app/actions/addMessage.js b/app/actions/addMessage.js new file mode 100644 index 0000000..7ac74c5 --- /dev/null +++ b/app/actions/addMessage.js @@ -0,0 +1,39 @@ +'use server'; +import connectDB from '@/config/database'; +import Message from '@/models/Message'; +import { getSessionUser } from '@/utils/getSessionUser'; +import { revalidatePath } from 'next/cache'; + +async function addMessage(previousState, formData) { + await connectDB(); + + const sessionUser = await getSessionUser(); + + if (!sessionUser || !sessionUser.user) { + return { error: 'You must be logged in to send a message' }; + } + + const { user } = sessionUser; + + const recipient = formData.get('recipient'); + + if (user.id === recipient) { + return { error: 'You can not send a message to yourself' }; + } + + const newMessage = new Message({ + sender: user.id, + recipient, + property: formData.get('property'), + name: formData.get('name'), + email: formData.get('email'), + phone: formData.get('phone'), + body: formData.get('message'), + }); + + await newMessage.save(); + + return { submitted: true }; +} + +export default addMessage; diff --git a/components/PropertyContactForm.jsx b/components/PropertyContactForm.jsx index 1f2decf..d8de8f7 100644 --- a/components/PropertyContactForm.jsx +++ b/components/PropertyContactForm.jsx @@ -1,81 +1,126 @@ +'use client'; +import { useEffect } from 'react'; +import { useFormState, useFormStatus } from 'react-dom'; +import { useSession } from 'next-auth/react'; +import { toast } from 'react-toastify'; +import addMessage from '@/app/actions/addMessage'; import { FaPaperPlane } from 'react-icons/fa'; -const PropertyContactForm = ({ property }) => { +const SubmitMessageButton = () => { + const status = useFormStatus(); return ( -