skip to Main Content

I’m trying to prevent toast, when component unmount, if user click onSubmit. Trying to do with useState, but it didn’t work for me.
My goal is to show user toast but if he click onSubmit, he shouldn’t have to see this toast. Toast should have appears when component unmount and we go away from page with form without submit.

const [formSubmitted, setFormSubmitted] = useState(false);

const formik = useFormik({
onSubmit: async (values) => {
  setFormSubmitted(true);
  // some logic
  navigate('/toAnotherPage');
})}

useEffect(() => {
  return () => {
    if (formik.dirty && !formSubmitted) {
      toast({                                //toast from chakraUI
        description: "Save info to draft",
        status: "success",
        duration: 3000,
        isClosable: false,
        containerStyle: {
          fontSize: "16px ",
          fontWeight: "350",
        },
      });
    }
  };
}, [formik.dirty, formSubmitted]);

2

Answers


  1. I would not go with the clean up function in useEffect approach. Try going for the route changed solution.

    Basically if route has changed and form is not submitted then render a toast message.

    import { useLocation } from 'react-router-dom'
    
    const location = useLocation()
    
    useEffect(()=>{
      if (formik.dirty && !formSubmitted) { 
       // your toast here
       }
    // Listens for location path name change as well
    },[location.pathname,formik.dirty,formSubmitted])
    

    This should be able to fulfill your use case of issuing a toast message and notifying the user that their.

    Login or Signup to reply.
  2. Can you try the below and let me know if it works?

           const [formSubmitted, setFormSubmitted] = useState(false);
            
            const formik = useFormik({
            onSubmit: async (values) => {
              setFormSubmitted(true);
              // some logic
            
            })}
        
        useEffect(()=>{
    if(formSubmitted){
        // form was submitted, do not show the toast and redirect the user
        navigate('/toAnotherPage');
    }
        },[formSubmitted]);
            
            useEffect(() => {
              return () => {
                if (formik.dirty && !formSubmitted) {
            console.log("use effect cleanup, showing toast now!!!");
                  toast({                                //toast from chakraUI
                    description: "Save info to draft",
                    status: "success",
                    duration: 3000,
                    isClosable: false,
                    containerStyle: {
                      fontSize: "16px ",
                      fontWeight: "350",
                    },
                  });
                }
              };
            }, [formik.dirty, formSubmitted]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search