From 3f19a4a0907797169b5347dc4ba7498996fe1f12 Mon Sep 17 00:00:00 2001 From: JSC Date: Sun, 13 Jul 2025 01:47:02 +0200 Subject: [PATCH] feat: add global socket event listeners for error handling and credits notifications in SocketContext --- src/contexts/SocketContext.tsx | 10 ++++++++++ src/pages/SoundboardPage.tsx | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/src/contexts/SocketContext.tsx b/src/contexts/SocketContext.tsx index 36d2d14..ed5cf5e 100644 --- a/src/contexts/SocketContext.tsx +++ b/src/contexts/SocketContext.tsx @@ -1,6 +1,7 @@ import { createContext, useContext, useEffect, useState } from "react"; import { io, Socket } from "socket.io-client"; import { useAuth } from "@/hooks/use-auth"; +import { toast } from "sonner"; interface SocketContextType { socket: Socket | null; @@ -67,6 +68,15 @@ export const SocketProvider: React.FC = ({ children }) => { setIsConnected(false); }); + // Global socket event listeners for toasts + newSocket.on("credits_required", (data) => { + toast.error(`Insufficient credits. Need ${data.credits_needed} credits.`); + }); + + newSocket.on("error", (data) => { + toast.error(data.message || "An error occurred"); + }); + setSocket(newSocket); // Clean up on unmount diff --git a/src/pages/SoundboardPage.tsx b/src/pages/SoundboardPage.tsx index ac67772..da84f4b 100644 --- a/src/pages/SoundboardPage.tsx +++ b/src/pages/SoundboardPage.tsx @@ -1,6 +1,7 @@ import { AddUrlDialog } from '@/components/AddUrlDialog' import { Button } from '@/components/ui/button' import { Card, CardContent } from '@/components/ui/card' +import { useSocket } from '@/contexts/SocketContext' import { useAddUrlShortcut } from '@/hooks/use-keyboard-shortcuts' import { useTheme } from '@/hooks/use-theme' import { formatDuration } from '@/lib/format-duration' @@ -105,6 +106,7 @@ export function SoundboardPage() { const [searchTerm, setSearchTerm] = useState('') const [addUrlDialogOpen, setAddUrlDialogOpen] = useState(false) const [currentColors, setCurrentColors] = useState(lightModeColors) + const { socket, isConnected } = useSocket() // Setup keyboard shortcut for CTRL+U useAddUrlShortcut(() => setAddUrlDialogOpen(true)) @@ -144,6 +146,13 @@ export function SoundboardPage() { const handlePlaySound = async (soundId: number) => { try { + // Try socket.io first if connected + if (socket && isConnected) { + socket.emit('play_sound', { soundId }) + return + } + + // Fallback to API request await apiService.post(`/api/soundboard/sounds/${soundId}/play`) } catch { setError('Failed to play sound')