I have a quite traditional problem but I haven't found a solution thus far searching around on Stackoverflow.
My problem is like this. I have a functional component which renders a form (using Formik). This component is rendered inside another Tab component that allows user to switch to another view. The UI also have another menu, buttons which also allow user to switch to different UI. Whenever a user changes a field in the form, I have a global flag in Redux store that marks it as dirty form.
What I want to achieve is that when user click on another tab or go to another UI view when form is dirty, system will show a dialog to confirm. If user agrees, he loses his changes and go to another view, if he doesn't, he will stay at current view with the form.
My current solution is that I have to add the confirming logic to every event handler that could bring user to another view such as Tab click, Menu click and this is tedious. Not to mention if the UI change in the future with more events for example more buttons, we have to keep adding this confirm logic to the onClick handler.
I also tried using useEffect as below in this component that returns a clean up function where I can add the confirm logic. This could show up the confirm dialog but it won't prevent React to unmount this form component and user ends up still go to another view.
useEffect(() => {
return () => {
//confirm logic here
}
}, [])
Is there a way for functional component handle this confirming logic itself?
These are some post I looked at but don't really find the answer. This one suggest using React router which we don't use in our project. The route actually doesn't change when user leave this form component. Show warning message before unmouting React component
Thanks for any advice!