I had to modify useCallbackPrompt a little bit, as it didn't work properly when the component wasn't unmounted after a "confirmed navigation".
exportfunctionuseCallbackPrompt(when){constnavigate=useNavigate();constlocation=useLocation();const[showPrompt,setShowPrompt]=useState(false);const[lastLocation,setLastLocation]=useState(null);const[confirmedNavigation,setConfirmedNavigation]=useState(false);constcancelNavigation=useCallback(()=>{setShowPrompt(false);},[]);// handle blocking when user click on another route prompt will be shownconsthandleBlockedNavigation=useCallback((nextLocation)=>{// in if condition we are checking next location and current location are equals or notif(!confirmedNavigation&&nextLocation.location.pathname!==location.pathname){setShowPrompt(true);setLastLocation(nextLocation);returnfalse;}returntrue;},// eslint-disable-next-line react-hooks/exhaustive-deps[confirmedNavigation,location]);constconfirmNavigation=useCallback(()=>{setShowPrompt(false);setConfirmedNavigation(true);},[]);useEffect(()=>{if(confirmedNavigation&&lastLocation){navigate(lastLocation.location.pathname);// Clean-up state on confirmed navigationsetConfirmedNavigation(false);}// eslint-disable-next-line react-hooks/exhaustive-deps},[confirmedNavigation,lastLocation]);useBlocker(handleBlockedNavigation,when);return[showPrompt,confirmNavigation,cancelNavigation];}
The changes are:
[confirmedNavigation, location] - added location to the handleBlockedNavigation hook. The location object changes and the location.pathname value remains outdated.
setConfirmedNavigation(false); - set after the programmatic navigation, state needed to be cleaned up so that future prompts are displayed.
Sorry if I'm not clear enough. I'm short of time and cannot elaborate a lot. Hopefully it will be useful for someone.
I am a Full Stack developer. I specialized in React JS, Next JS, Node JS, Gatsby, JavaScript, Angular, GraphQL. I'm passionate about new technologies and I keep learning all the time.
I had to modify useCallbackPrompt a little bit, as it didn't work properly when the component wasn't unmounted after a "confirmed navigation".
The changes are:
[confirmedNavigation, location]- added location to the handleBlockedNavigation hook. The location object changes and thelocation.pathnamevalue remains outdated.setConfirmedNavigation(false);- set after the programmatic navigation, state needed to be cleaned up so that future prompts are displayed.Sorry if I'm not clear enough. I'm short of time and cannot elaborate a lot. Hopefully it will be useful for someone.
Thanks.
Thank you Miguel Palacio for fixing :)