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
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.
This should be able to fulfill your use case of issuing a toast message and notifying the user that their.
Can you try the below and let me know if it works?