dcs-retribution/client/src/hooks/useEventSteam.ts
2022-03-01 21:08:08 -08:00

27 lines
629 B
TypeScript

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;