Next.js Discord

Discord Forum

Toast after a server action

Answered
Pyramid ant posted this in #help-forum
Open in Discord
Pyramid antOP
action.ts

"use server";

import prisma from "@/utils/prisma";

type FormDataType = {
  name: string;
  email: string;
  message: string;
  subject: string;
  pno?: string;
};

export const addDoc = async (formData: FormData) => {
  try {
    if (
      !formData.get("name") ||
      !formData.get("email") ||
      !formData.get("message") ||
      !formData.get("subject")
    ) {
      return;
    }

    const rawFormData: FormDataType = {
      name: formData.get("name") as string,
      email: formData.get("email") as string,
      message: formData.get("message") as string,
      subject: formData.get("subject") as string,
      pno: formData.get("pno") as string,
    };

    await prisma.contact.create({
      data: {
        name: rawFormData.name,
        email: rawFormData.email,
        message: rawFormData.message,
        subject: rawFormData.subject,
        phone: rawFormData.pno,
      },
    });
  } catch (error) {
    console.log(error);
  }
};


Form.tsx

const Form = () => {
  return (
    <form className={styles.form} autoComplete="off" action={addDoc}>
     ...
    </form>
  );
};


i basically wanna toast a message if the action has been succesfull but i'm getting the following error, whenever i'm using the toast function
Answered by フェイン (Fane)
const res = await addDoc(data)
if (res?.error) {
toast.error...
}
View full answer

10 Replies

Pyramid antOP
But if an error occurs
i need to toastthe error, which is confusing to me
i mean i could return the response and check for its response and conditionally toast the message
const res = await addDoc(data)
if (res?.error) {
toast.error...
}
Answer
Pyramid antOP
but is thatright?
@フェイン (Fane) const res = await addDoc(data) if (res?.error) { toast.error... }
Pyramid antOP
right exactly what i had in mind
yeah like ian said, you can return the result/error on the server action
Pyramid antOP
perfect
thank you everyone!