SSE-REACT
🧩 Syntax:
import React, {
createContext,
useState,
useEffect,
useCallback
} from 'react';
import {
toast
} from 'react-toastify';
export const NotificationsContext = createContext();
export const NotificationsProvider = ({
children
}) => {
const [notifications, setNotifications] = useState([]);
const [unreadCount, setUnreadCount] = useState(0);
const handleNewNotification = useCallback((notification) => {
setNotifications((prev) => [notification, ...prev]);
setUnreadCount((prev) => prev + 1);
toast.info(notification.message, {
position: 'top-right',
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
}, []);
useEffect(() => {
const eventSource = new EventSource('/api/notifications/stream', {
withCredentials: true,
});
eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
handleNewNotification(data);
} catch (error) {
console.error('Error parsing SSE data:', error);
}
};
eventSource.onerror = (error) => {
console.error('SSE connection error:', error);
eventSource.close();
};
return () => {
eventSource.close();
};
}, [handleNewNotification]);
return (
<NotificationsContext.Provider value = {{
notifications,
unreadCount,
setUnreadCount
}}>
{children}
<NotificationsContext.Provider>
);
};