I want to close event source after user logout. My codes are below. When user logging out push notifications are still coming. My questions is how to close event source?
const eventSource = new EventSource(`${environment.notificationUrl}/subscribe?
token=${token}`);
if (!token) {
eventSource.removeAllEventListeners()
eventSource.close()
return;
}
eventSource.addEventListener('message', (event: any) => {
---- some codes here ----
}
Technically, event listeners should be subscribed inside useEffect and keep tracking when user logged out.
const NotificationSubscriptionManager = () => {
const eventSource =
new EventSource(`${environment.notificationUrl}/subscribe?
token=${token}`);
const subScribeToNotifications = () => {
eventSource.addEventListener("message", (event: any) => {
/// ---- some codes here ----
});
};
const unsubScribeToNotifications = () => {
eventSource.removeAllEventListeners();
eventSource.close();
};
useEffect(() => {
if (!token) {
return unsubScribeToNotifications();
}
// Subscribe to notification events
subScribeToNotifications();
// Cancel all subscription when component unmount to avoid
// memory leak
return () => {
unsubScribeToNotifications();
};
}, [token]);
};