fix: resolve notification sound autoplay block and polling delay

- Prevented sound from triggering on initial page load.

- Confirmed polling interval is set to 10 seconds for real-time alerts.
This commit is contained in:
Cauê Faleiros
2026-03-10 11:09:03 -03:00
parent 754c1e2a21
commit d3587344a3

View File

@@ -44,13 +44,14 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
const [notifications, setNotifications] = useState<any[]>([]); const [notifications, setNotifications] = useState<any[]>([]);
const [showNotifications, setShowNotifications] = useState(false); const [showNotifications, setShowNotifications] = useState(false);
const unreadCount = notifications.filter(n => !n.is_read).length; const unreadCount = notifications.filter(n => !n.is_read).length;
const previousUnreadCountRef = React.useRef(unreadCount); const previousUnreadCountRef = React.useRef(0);
const isInitialLoadRef = React.useRef(true);
const playNotificationSound = () => { const playNotificationSound = () => {
if (currentUser?.sound_enabled !== false) { if (currentUser?.sound_enabled !== false) {
const audio = new Audio('/audio/notification.mp3'); const audio = new Audio('/audio/notification.mp3');
audio.volume = 0.5; audio.volume = 0.5;
audio.play().catch(e => console.log('Audio play failed (browser policy):', e)); audio.play().catch(e => console.log('Audio play failed:', e));
} }
}; };
@@ -58,12 +59,15 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
const data = await getNotifications(); const data = await getNotifications();
setNotifications(data); setNotifications(data);
// Check if there are new unread notifications
const newUnreadCount = data.filter((n: any) => !n.is_read).length; const newUnreadCount = data.filter((n: any) => !n.is_read).length;
if (newUnreadCount > previousUnreadCountRef.current) {
// Only play sound if it's NOT the first load AND the count actually increased
if (!isInitialLoadRef.current && newUnreadCount > previousUnreadCountRef.current) {
playNotificationSound(); playNotificationSound();
} }
previousUnreadCountRef.current = newUnreadCount; previousUnreadCountRef.current = newUnreadCount;
isInitialLoadRef.current = false;
}; };
useEffect(() => { useEffect(() => {
@@ -110,7 +114,7 @@ export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) =>
}; };
fetchCurrentUser(); fetchCurrentUser();
loadNotifications(); loadNotifications();
const interval = setInterval(loadNotifications, 60000); const interval = setInterval(loadNotifications, 10000);
return () => clearInterval(interval); return () => clearInterval(interval);
}, [navigate]); }, [navigate]);