I’m trying to call a logout function when the network changes in my React application. However, as soon as I log in, my useEffect hook automatically triggers, causing an unintended logout, even though the network hasn’t actually changed. I’d like the logout function to be called only when there’s a genuine network change (such as a disconnect or reconnect event), not on minor variations or when the app initially loads.
I am testing this on chrome browser. I am using navigator api in my useEffect with event listener in my App.jsx file but its not working out. It randomly logs out the user.
const { handleLogout } = useLogout()
const whenUserIsIdle = () => {
if (isUserAuthenticated)
handleLogout()
}
useIdleTimer({
onIdle: whenUserIsIdle,
timeout: 300000, //5 minutes
throttle: 500, // checks after 500ms
});
useEffect(() => {
const handleNetworkChange = () => {
console.log('connection network change effect',connection);
if (localStorage.getItem('authToken')) {
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
// Perform a condition check to prevent unnecessary logouts
if (connection && connection.downlink > 0) { // for example, checking if downlink speed is above 0
handleLogout();
}
}
};
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
connection.addEventListener('change', handleNetworkChange);
}
return () => {
if (connection) {
connection.removeEventListener('change', handleNetworkChange);
}
};
}, [handleLogout]);
my custom logout hook:
const useLogout = () => {
const dispatch = useDispatch();
const handleNavigateToRoot = useNavigatetoRoot();
// Define the function to handle successful logout
const onSuccessfullLogout = (response) => {
handleNavigateToRoot()
};
// Get mutate function from the usePostDataToServer hook
const { mutate } = usePostDataToServer({
onPostReqSuccess: onSuccessfullLogout,
dispatch,
});
// Define a function to handle logout
const handleLogout = () => {
const API_URL = `${BASE_URL}${ENDPOINTS.LOGOUT}`;
mutate({ API_URL, dispatch });
};
return { handleLogout };
};
export default useLogout;