Add websocket handling for selected flights.

This commit is contained in:
Dan Albert
2022-03-01 20:42:59 -08:00
parent 6d29bfdf65
commit 8e8bbe84f3
13 changed files with 190 additions and 13 deletions

View File

@@ -0,0 +1,26 @@
import { useCallback, useEffect } from "react";
import { handleStreamedEvents } from "../api/eventstream";
import { useAppDispatch } from "../app/hooks";
import { useSocket } from "./useSocket";
export const useEventStream = () => {
const ws = useSocket();
const dispatch = useAppDispatch();
const onMessage = useCallback(
(message) => {
handleStreamedEvents(dispatch, JSON.parse(message.data));
},
[dispatch]
);
useEffect(() => {
ws.addEventListener("message", onMessage);
return () => {
ws.removeEventListener("message", onMessage);
};
});
};
export default useEventStream;

View File

@@ -0,0 +1,37 @@
import { ControlPoint } from "../api/controlpoint";
import { Flight } from "../api/flight";
import backend from "../api/backend";
import { registerFlight } from "../api/flightsSlice";
import { setControlPoints } from "../api/controlPointsSlice";
import { useAppDispatch } from "../app/hooks";
import { useEffect } from "react";
// TODO: This should probably be distinct useControlPoints, useFlights, etc that
// are smart enough to only initialize once which get called in the components
// that use them rather than forcibly loading the whole game in the root
// component.
export const useInitialGameState = () => {
const dispatch = useAppDispatch();
useEffect(() => {
backend
.get("/control-points")
.catch((error) => console.log(`Error fetching control points: ${error}`))
.then((response) => {
if (response != null) {
dispatch(setControlPoints(response.data as ControlPoint[]));
}
});
backend
.get("/flights?with_waypoints=true")
.catch((error) => console.log(`Error fetching flights: ${error}`))
.then((response) => {
if (response != null) {
for (const flight of response.data) {
dispatch(registerFlight(flight as Flight));
}
}
});
});
};
export default useInitialGameState;

View File

@@ -0,0 +1,8 @@
import { SocketContext } from "../components/socketprovider/socketprovider";
import { useContext } from "react";
export const useSocket = () => {
const socket = useContext(SocketContext);
return socket;
};