From 376ffa651a74c19ba6182bd1067efec82a90f95d Mon Sep 17 00:00:00 2001 From: Kakabay <2kakabayashyrberdyew@gmail.com> Date: Sat, 25 Jan 2025 18:40:18 +0500 Subject: [PATCH] websocket message types changed --- components/lottery/LotteryWinnersSection.tsx | 40 ++++++++++++----- .../lottery/winners/LotteryWinnersList.tsx | 22 ++++++--- hooks/useWebSocketLottery.ts | 45 ++++++++++--------- typings/lottery/lottery.types.ts | 4 +- 4 files changed, 72 insertions(+), 39 deletions(-) diff --git a/components/lottery/LotteryWinnersSection.tsx b/components/lottery/LotteryWinnersSection.tsx index a8a0728..a65d6d8 100644 --- a/components/lottery/LotteryWinnersSection.tsx +++ b/components/lottery/LotteryWinnersSection.tsx @@ -3,8 +3,6 @@ import { useLotteryAuth } from "@/store/useLotteryAuth"; import { LotteryWinnerDataSimplified } from "@/typings/lottery/lottery.types"; import LotteryWinnersList from "./winners/LotteryWinnersList"; import LotterySlotCounter from "./slotCounter/LotterySlotCounter"; -import ReactConfetti from "react-confetti"; -import { useWindowSize } from "react-use"; import AnimatedText from "@/components/common/AnimatedText"; import { useWebsocketLottery } from "@/hooks/useWebSocketLottery"; import Confetti from "../common/Confetti"; @@ -40,11 +38,11 @@ const LotteryWinnersSection = ({ `${WEBSOCKET_URL}${lotteryData?.data.sms_number}` ); - // Simulate WebSocket messages for testing + // Simulate WebSocket message for testing const simulateMessage = () => { const dummyWinner: LotteryWinnerDataSimplified = { - client: `9936${Math.floor(10000000 + Math.random() * 90000000)}`, - winner_no: winners.length + 1, + phone: `9936${Math.floor(10000000 + Math.random() * 90000000)}`, // Generate random client number + winner_no: winners.length + 1, // Increment winner number ticket: `${Math.floor(Math.random() * 99) .toString() .padStart(2, "0")}-${Math.floor(Math.random() * 99) @@ -55,17 +53,28 @@ const LotteryWinnersSection = ({ .toString() .padStart(2, "0")}-${Math.floor(Math.random() * 99) .toString() - .padStart(2, "0")}`, + .padStart(2, "0")}`, // Generate random ticket }; + console.log("πŸ“© Simulated Message:", dummyWinner); // Log the simulated message setMessageQueue((prevQueue) => [...prevQueue, dummyWinner]); }; + // useEffect(() => { + // const interval = setInterval(() => { + // simulateMessage(); + // }, 20000); // Trigger every 10 seconds + + // return () => clearInterval(interval); // Clean up interval on unmount + // }, []); + // Initialize winners from lottery data useEffect(() => { + console.log("🎟️ Lottery Data:", lotteryData); + if (lotteryData && lotteryData.data.winners.length > 0) { const simplifiedWinners = lotteryData.data.winners.map((winner) => ({ - client: winner.client, + phone: winner.client, winner_no: winner.winner_no, ticket: winner.ticket, })); @@ -74,7 +83,7 @@ const LotteryWinnersSection = ({ const lastWinner = simplifiedWinners[simplifiedWinners.length - 1]; setWinnerSelectingStatus("selected"); setTopText(`${lastWinner.winner_no}-nji Γ½eňiji`); - setBottomText(lastWinner.client); + setBottomText(lastWinner.phone); setIsConfettiActive(true); } }, [lotteryData]); @@ -84,9 +93,13 @@ const LotteryWinnersSection = ({ const unsubscribe = subscribeToMessages((event) => { try { const newWinner: LotteryWinnerDataSimplified = JSON.parse(event.data); + console.log("πŸ“© WebSocket Message Received:", newWinner); // Log the parsed message // Add new message to the queue - setMessageQueue((prevQueue) => [...prevQueue, newWinner]); + setMessageQueue((prevQueue) => { + console.log("πŸ“₯ Adding to Queue:", newWinner); + return [...prevQueue, newWinner]; + }); } catch (error) { console.error("Error parsing WebSocket message:", error); } @@ -97,6 +110,8 @@ const LotteryWinnersSection = ({ // Process queue when a new message is added useEffect(() => { + console.log("πŸ“‹ Current Message Queue:", messageQueue); + if (!isProcessing && messageQueue.length > 0) { processQueue(); } @@ -109,6 +124,8 @@ const LotteryWinnersSection = ({ setIsProcessing(true); // Lock processing const message = messageQueue[0]; // Get the first message in the queue + console.log("βš™οΈ Processing Message:", message); // Debug Log 4: Log the message being processed + try { await handleMessage(message); // Process the message } catch (error) { @@ -121,6 +138,7 @@ const LotteryWinnersSection = ({ // Handle the logic for processing a single WebSocket message const handleMessage = async (winner: LotteryWinnerDataSimplified) => { + console.log("⬇️ Updating Top and Bottom Text:", winner); // Debug Log 5: Log winner data before setting states setIsConfettiActive(false); setTopText(`${winner.winner_no}-nji Γ½eňiji saΓ½lanΓ½ar`); setBottomText("..."); @@ -133,7 +151,9 @@ const LotteryWinnersSection = ({ // Finalize winner selection setTopText(`${winner.winner_no}-nji Γ½eňiji`); - setBottomText(winner.client); + setBottomText(winner.phone); + console.log("⬇️ Finalized Bottom Text:", winner.phone); // Debug Log 6: Log the final bottomText update + setWinnerSelectingStatus("selected"); setIsConfettiActive(true); diff --git a/components/lottery/winners/LotteryWinnersList.tsx b/components/lottery/winners/LotteryWinnersList.tsx index 44579c6..ce9e7d8 100644 --- a/components/lottery/winners/LotteryWinnersList.tsx +++ b/components/lottery/winners/LotteryWinnersList.tsx @@ -1,9 +1,16 @@ -import { LotteryWinnerData, LotteryWinnerDataSimplified } from '@/typings/lottery/lottery.types'; -import LotteryWinner from './LotteryWinner'; -import { motion, AnimatePresence } from 'framer-motion'; -import { v4 } from 'uuid'; +import { + LotteryWinnerData, + LotteryWinnerDataSimplified, +} from "@/typings/lottery/lottery.types"; +import LotteryWinner from "./LotteryWinner"; +import { motion, AnimatePresence } from "framer-motion"; +import { v4 } from "uuid"; -const LotteryWinnersList = ({ winners }: { winners: LotteryWinnerDataSimplified[] }) => { +const LotteryWinnersList = ({ + winners, +}: { + winners: LotteryWinnerDataSimplified[]; +}) => { return (
@@ -11,11 +18,12 @@ const LotteryWinnersList = ({ winners }: { winners: LotteryWinnerDataSimplified[
+ className="grid min-[1025px]:grid-cols-3 min-[700px]:grid-cols-2 grid-cols-1 gap-x-2 gap-y-4 w-full lottery-winner-list" + > {winners.map((item, index) => ( { const [wsStatus, setWsStatus] = useState< @@ -14,15 +14,15 @@ export const useWebsocketLottery = (url: string) => { const setupWebSocket = () => { if (!isMounted) return; - console.log("πŸ”„ Connecting to WebSocket..."); + console.log("πŸ”„ [WebSocket] Connecting..."); const socket = new WebSocket(url); wsRef.current = socket; socket.onopen = () => { if (!isMounted) return; - console.log("βœ… WebSocket connected"); - console.log("WebSocket url", url); + console.log("βœ… [WebSocket] Connected"); + console.log("πŸ”— [WebSocket URL]:", url); setWsStatus("connected"); if (reconnectTimeoutRef.current) clearTimeout(reconnectTimeoutRef.current); @@ -31,21 +31,21 @@ export const useWebsocketLottery = (url: string) => { socket.onmessage = (event) => { if (!isMounted) return; - console.log("πŸ“© Message received:", event.data); + console.log("πŸ“© [WebSocket] Message received:", event.data); messageListeners.current.forEach((listener) => listener(event)); }; socket.onerror = () => { if (!isMounted) return; - console.error("❌ WebSocket error"); + console.error("❌ [WebSocket] Error occurred"); setWsStatus("error"); }; socket.onclose = () => { if (!isMounted) return; - console.log("❌ WebSocket closed"); + console.log("❌ [WebSocket] Closed"); setWsStatus("closed"); reconnectWebSocket(); }; @@ -54,7 +54,7 @@ export const useWebsocketLottery = (url: string) => { const reconnectWebSocket = () => { if (!isMounted) return; - console.log("πŸ”„ Reconnecting to WebSocket..."); + console.log("πŸ”„ [WebSocket] Reconnecting in 5 seconds..."); reconnectTimeoutRef.current = setTimeout(() => { setupWebSocket(); }, 5000); @@ -63,7 +63,7 @@ export const useWebsocketLottery = (url: string) => { setupWebSocket(); return () => { - console.log("πŸ”Œ Cleaning up WebSocket connection..."); + console.log("πŸ”Œ [WebSocket] Cleaning up..."); isMounted = false; if (wsRef.current) { @@ -77,21 +77,26 @@ export const useWebsocketLottery = (url: string) => { }; }, [url]); - const sendPing = () => { + const sendPing = useCallback(() => { if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { - console.log("πŸ“€ Sending ping"); + console.log("πŸ“€ [WebSocket] Sending ping"); wsRef.current.send(JSON.stringify({ type: "ping" })); } - }; + }, []); - const subscribeToMessages = (listener: (event: MessageEvent) => void) => { - messageListeners.current.push(listener); - return () => { - messageListeners.current = messageListeners.current.filter( - (l) => l !== listener - ); - }; - }; + const subscribeToMessages = useCallback( + (listener: (event: MessageEvent) => void) => { + console.log("πŸ‘‚ [WebSocket] Subscribing to messages"); + messageListeners.current.push(listener); + return () => { + console.log("❌ [WebSocket] Unsubscribing from messages"); + messageListeners.current = messageListeners.current.filter( + (l) => l !== listener + ); + }; + }, + [] // Empty array ensures it's memoized + ); return { wsStatus, sendPing, subscribeToMessages }; }; diff --git a/typings/lottery/lottery.types.ts b/typings/lottery/lottery.types.ts index bc55c3c..e25077b 100644 --- a/typings/lottery/lottery.types.ts +++ b/typings/lottery/lottery.types.ts @@ -23,9 +23,9 @@ export interface LotteryResponse { } export interface LotteryWinnerDataSimplified { - client: string; + phone: string; winner_no: number; ticket: string; } -export type LotteryStatus = 'not-started' | 'started' | 'ended'; +export type LotteryStatus = "not-started" | "started" | "ended";