feat: add global socket event listeners for error handling and credits notifications in SocketContext
This commit is contained in:
@@ -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<SocketProviderProps> = ({ 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
|
||||
|
||||
@@ -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<string[]>(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')
|
||||
|
||||
Reference in New Issue
Block a user