This is my GameContext
file:
import { createContext } from "react";
export const GameContext = createContext(null)
In my App.js
, I initialised all the values I wish to wrap my context with so that all other child components can use it:
const gameContextValue = {
isGameStarted,
setGameStarted,
isPlayerTurn,
setPlayerTurn,
roomId,
};
return (
<GameContext.Provider value={gameContextValue}>
<BrowserRouter>
<Routes>
<Route path="/register" element={<Register />} />
<Route path="/login" element={<Login />} />
<Route path="/" element={<JoinGame />} />
<Route path="/game" element={<Game />} />
</Routes>
</BrowserRouter>
</GameContext.Provider>
);
}
Then,I use useContext()
to use these values in my child component:
const {
isGameStarted,
setGameStarted,
isPlayerTurn,
setPlayerTurn,
roomId,
} = useContext(GameContext);
const Game = () => {
const handleGameStart = () => {
setGameStarted(true);
console.log("value of isGameStarted: ", isGameStarted) //shows false
if (start) {
setPlayerTurn(true);
} else {
setPlayerTurn(false);
}
});
};
}
useEffect(() => {
handleGameUpdate();
handleGameStart();
}, []);
Why does my useState updates not work? I'm not sure what i'm doing wrong...I would really appreciate any advice (been staring at my code for 2 hrs to no avail...)