usePlayerScores.jsx 803 B

12345678910111213141516171819202122232425
  1. import { useState, useEffect } from 'react';
  2. import { gameInfo } from '../domain/GGSHService';
  3. import { useGameId } from '../domain/gameStore';
  4. export default () => {
  5. const gameId = useGameId();
  6. const [scores, setScores] = useState(null);
  7. useEffect(() => {
  8. // define how to fetch scores
  9. const fetchInfo = async () => {
  10. const { players } = await gameInfo();
  11. // TODO would be nice to only setScores on a change - maybe have back-end provide timestamp?
  12. setScores(players);
  13. };
  14. // when the hook triggers, fetch the game info
  15. fetchInfo();
  16. // and do it again every 5 seconds after
  17. const interval = setInterval(() => fetchInfo(), 5000);
  18. // and return a clean-up callback
  19. return () => { clearInterval(interval) };
  20. }, [gameId]);
  21. return scores;
  22. }