Reputation: 306
When I close browser or tab it should call log out api. can anybody suggest any solution on it?
Upvotes: 4
Views: 7446
Reputation: 2019
I tried all the above methods and they all have some issues. For example, "beforeunload" listener calls every time when the user navigates to another screen but we only want to call it on the tab close. Here's how I fixed it.
1- First store your token in sessionStorage
sessionStorage.setItem("logged", true);
2- Now you can check if the logged variable value is false then you can call the logout function.
const isLogged = sessionStorage.getItem("logged");
useEffect(() => {
if (!isLogged) {
dispatch(logout());
}
}, []);
Upvotes: 0
Reputation: 673
You need to call the logout API right before your component unmounts.
For functional components, the clean up function is the place:
const MyComponent = (props) => {
useEffect(() => {
return () => {
// Logout logic goes here
}
}, []);
}
For class-based components, it's the componentWillUnmount()
function:
class MyComponent extends React.Component {
componentWillUnmount() {
// Logout logic goes here
}
}
But wait, that will trigger the logout every time the user moves away from the page, even without closing the browser/tab. For that, you could make use of a state variable, and handle outbound navigations based on its value.
For example, create an isOnlineNav
state variable that is false
by default, and you set it to true
whenever the user moves away by interacting with the app (link clicks, navigation, form submission, redirects, etc.). When the user closes the browser tab, the value remains false
, and you could use the state to trigger logout.
Example in a functional component:
const MyComponent = (props) => {
const [isOnlineNav, setIsOnlineNav] = useState(false);
const goHome = () => {
setIsOnlineNav(true);
window.location = "/";
}
useEffect(() => {
return () => {
if (!isOnlineNav) {
// Logout logic goes here
}
}
}, []);
return (
<button onClick={goHome}>Go Home</button>
)
}
It could cause unexpected bugs if you're not careful. Below are at least two of those possible scenarios.
<Link>
or <a>
tag with a direct path to go to).Upvotes: 0
Reputation: 21
This is an illustration that I came about, link included but it does not factor in the refresh part so still figuring that out.
import {useEffect} from 'react';
const App = () => {
let logOut = () => {
localStorage.clear();
navigate('/login')
}
useEffect(() => {
const handleTabClose = event => {
event.preventDefault();
console.log('beforeunload event triggered');
return (event.returnValue = 'Are you sure you want to exit?');
};
window.addEventListener('beforeunload', handleTabClose);
return () => {
logOut()
window.removeEventListener('beforeunload', handleTabClose);
};
}, []);
return (
<div>
<h2>hello world</h2>
</div>
);
};
export default App;
[https://bobbyhadz.com/blog/react-handle-tab-close-event][1]
Upvotes: 1