In react I tried to redirect user from current page to another page after reload by using onunload & onbeforeunload. but after first reload it shows the url changed and comeback to current page again. and after second reload it goes to redirected page. These are some code I tried...
Test 001: Just after confirmation / "Leave Page" button clicked, it should redirect. Fact is it goes to the page and redirect to the previous page. >_<
import { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
useEffect(() => {
const handleBeforeUnload = (event) => {
// Prevent the default dialog box from showing
event.preventDefault();
// Redirect the user to the desired page
history.push('/redirected-page');
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [history]);
// Rest of your component code...
return (
// JSX for your component...
);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.0/react-dom.min.js"></script>
Test 002: Then I thought it might be the timing issue and I set a timer. Now things goes worse! it doesn't go there.
useEffect(() => {
const handleBeforeUnload = (event) => {
event.preventDefault();
// Delay the redirection by 100 milliseconds
setTimeout(() => {
history.push('/Applicant-profile');
}, 100);
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [history]);