in react. is the file below to much responsibility for a context. what are the best…
- User
in react. is the file below to much responsibility for a context. what are the best practices around context and why.
import React, { createContext, useContext, useEffect } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import useGameStore from '../store/useGameStore'; import useRoundStore from '../store/useRoundStore'; import { Game, Round } from '../types';
interface GameContextType { gameId: string | null; gameData: Game | null; roundData: Round | null; }
const GameContext = createContext<GameContextType | undefined>(undefined);
export const GameProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const { gameId: urlGameId } = useParams<{ gameId: string }>(); const navigate = useNavigate(); const { gameId, gameData, setGameId, syncGameData } = useGameStore(); const { syncRoundData, roundData } = useRoundStore();
useEffect(() => { if (urlGameId && urlGameId !== gameId) { console.log('urlGameId is', urlGameId); setGameId(urlGameId); } else if (!urlGameId && gameId) { navigate(
/game-lobby/${gameId}); }if (gameId && !gameData) { syncGameData(gameId); }}, [urlGameId, gameId, gameData, setGameId, navigate, syncGameData]);
useEffect(() => { if (gameId === null && urlGameId === null && !gameData) { console.log('gameId is null and gameData is null'); navigate('/game-not-found'); } }, [gameId, gameData, navigate, urlGameId]);
useEffect(() => { if (gameId && gameData && gameData.status === 'IN_PROGRESS' && gameData.currentRound > 0) { syncRoundData(gameId, gameData.currentRound); } }, [gameId, gameData, syncRoundData]);
return <GameContext.Provider value={{ gameId, gameData, roundData }}>{children}</GameContext.Provider>; };
export const useGame = () => { const context = useContext(GameContext); if (context === undefined) { throw new Error('useGame must be used within a GameProvider'); } return context; };
- Assistant