|
@@ -1,17 +1,30 @@
|
|
|
import { useState, useEffect } from 'react';
|
|
|
import dequal from 'dequal';
|
|
|
-import { gameInfo } from '../domain/apiMethods';
|
|
|
+import { getGameConfig, getGameCoords, getPlayers, getLinkedGame } from '../domain/apiMethods';
|
|
|
import { useGameId } from '../domain/gameStore';
|
|
|
|
|
|
-export default () => {
|
|
|
+const useSingleCall = apiCall => {
|
|
|
const gameId = useGameId();
|
|
|
- const [info, setInfo] = useState({});
|
|
|
+ const [info, setInfo] = useState(null);
|
|
|
+
|
|
|
+ useEffect(() => { apiCall(gameId).then(setInfo) }, [gameId, apiCall]);
|
|
|
+
|
|
|
+ return info;
|
|
|
+}
|
|
|
+
|
|
|
+export const useGameConfig = () => useSingleCall(getGameConfig) ?? {};
|
|
|
+
|
|
|
+export const useGameCoords = () => useSingleCall(getGameCoords);
|
|
|
+
|
|
|
+const useAutoRefresh = apiCall => {
|
|
|
+ const gameId = useGameId();
|
|
|
+ const [info, setInfo] = useState(null);
|
|
|
|
|
|
useEffect(() => {
|
|
|
- // define how to fetch scores
|
|
|
+ // define how to fetch info
|
|
|
const fetchInfo = async () => {
|
|
|
- const newInfo = await gameInfo(gameId);
|
|
|
- // TODO maybe have back-end provide timestamp? to avoid this check
|
|
|
+ const newInfo = await apiCall(gameId);
|
|
|
+ // TODO make equality an argument? to avoid doing dequal on deep structures?
|
|
|
if (!dequal(info, newInfo)) {
|
|
|
setInfo(newInfo);
|
|
|
}
|
|
@@ -22,7 +35,11 @@ export default () => {
|
|
|
const interval = setInterval(() => fetchInfo(), 5000);
|
|
|
// and return a clean-up callback
|
|
|
return () => { clearInterval(interval) };
|
|
|
- }, [gameId, info]);
|
|
|
+ }, [gameId, apiCall, info]);
|
|
|
|
|
|
return info;
|
|
|
}
|
|
|
+
|
|
|
+export const usePlayers = () => useAutoRefresh(getPlayers);
|
|
|
+
|
|
|
+export const useLinkedGame = () => useAutoRefresh(getLinkedGame);
|