skip to Main Content

I’m looking into React and React Hook Form, I managed to display custom messages below the inputs but I also want to display an alert using react-toastify to let the user know about all the errors. How can I add a function a part from the existing error message?

I want to have something like errors && callMyFunction().

2

Answers


  1. I went through the React Hook Form docs and I realised the errors property of the formState returns an object and not an array (https://react-hook-form.com/docs/useform/formstate). Therefore, If you want to trigger a toast whenever there is an error, then you can just achieve this with the useEffect hook using this reproducible code I have written:

    import { useEffect } from "react"
    import { useForm } from "react-hook-form";
    import { toast } from "react-toastify";
    
    const ContactPage = () => {
      const { formState: { errors }, } = useForm({
        defaultValues: {
          firstName: "",
          lastName: "",
        },
        mode: "all",
      });
    
      useEffect(() => {
        const errorMessages = Object.values(errors);
    
        if (errorMessages.length > 0) {
          for (const error of errorMessages) {
            toast.error(error.message, {
              position: "top-center",
              hideProgressBar: true,
              toastId: error.message, //This prevents the toast from opening the same error message multiple times whenever errors change
            });
          }
        }
      }, [Object.values(errors).length]);
    }
    
    

    I hope this solves it for you.

    Login or Signup to reply.
  2. The function handleSubmit receives two parameters:

    1. onValid for handling successful submissions
    2. onInvalid for handling errors.

    onInvalid function is triggered whenever the form is submitted with errors.

    Here’s an example:

    const onError = (fieldsErrors) => {
      for (const fieldName in fieldsErrors) {
        toast.error(`Error in ${fieldName}: ${fieldsErrors[fieldName].message}`);
      }
    };
    

    Then, in your form:

    return (
      <form onSubmit={handleSubmit(onSubmit, onError)}>
      );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search