import * as React from "react"; import { FunctionComponent, useEffect, useState } from "react"; import { channel_on_live_games, channel_subscribe_live_games, channel_unsubscribe_live_games, LiveGameSummary, } from "@mancala/core"; import { useTranslation } from "react-i18next"; import { Context } from "../../context/context"; import GameCard from "./GameCard"; import HomeSection from "./HomeSection"; // Live games, updated as they are played; hidden while nothing is being played. const LiveGamesSection: FunctionComponent<{ context: Context }> = ({ context }) => { const { t } = useTranslation(); const [games, setGames] = useState([]); useEffect(() => { const onLiveGames = (message: { games: LiveGameSummary[] }) => setGames(message.games); // Subscribe whenever the connection is (re)established; the server forgets subscriptions of offline users. const subscribe = () => context.rtmt.sendMessage(channel_subscribe_live_games, {}); context.rtmt.addMessageListener(channel_on_live_games, onLiveGames); context.rtmt.on("open", subscribe); if (context.rtmt.connectionState === "connected") subscribe(); return () => { context.rtmt.off("open", subscribe); context.rtmt.removeMessageListener(channel_on_live_games, onLiveGames); if (context.rtmt.connectionState === "connected") context.rtmt.sendMessage(channel_unsubscribe_live_games, {}); }; }, []); if (games.length === 0) return <>; return ( {games.map((game) => ( ))} ); }; export default LiveGamesSection;