From 29da0d32246a34bd98f0eadb05e389a9d1c8465f Mon Sep 17 00:00:00 2001 From: claustra01 Date: Thu, 15 Aug 2024 16:36:35 +0900 Subject: [PATCH] refactor: replace to socket hook in yatai component --- src/pages/yatai/index.tsx | 35 ++++++++++------------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/src/pages/yatai/index.tsx b/src/pages/yatai/index.tsx index 61714b9..8a4515d 100644 --- a/src/pages/yatai/index.tsx +++ b/src/pages/yatai/index.tsx @@ -16,6 +16,7 @@ import { type Target, } from "../../type/shooting"; import styles from "./index.module.css"; +import { useSocketReciever } from "../../hooks/useSocketReciever"; const YataiStage = memo(() => { // 土台 @@ -49,6 +50,7 @@ const YataiStage = memo(() => { // 的 const Target = (props: ThreeElements["mesh"]) => { + const { onMessage } = useSocketReciever(); const position = props.position as [number, number, number]; const args: [number, number, number] = [0.7, 2, 0.7]; @@ -58,21 +60,13 @@ const YataiStage = memo(() => { args: args, })); - const socketRef = useSocketRefStore((state) => state.socketRef); - useEffect(() => { - const onMessage = (event: MessageEvent) => { - const data = JSON.parse(event.data); + onMessage((data) => { if (data.message_type === MessageType.Action) { shotTarget(data); } - }; - const currentSocketRef = socketRef?.current; - currentSocketRef?.addEventListener("message", onMessage); - return () => { - currentSocketRef?.removeEventListener("message", onMessage); - }; - }, [socketRef]); + }); + }, [onMessage]); // TODO: これらは一人用,いつかマルチプレイヤー対応する const [target, setTarget] = useState(undefined); @@ -154,25 +148,16 @@ const YataiStage = memo(() => { }); const TargetOverlay = () => { - const socketRef = useSocketRefStore((state) => state.socketRef); + const { onMessage } = useSocketReciever(); useEffect(() => { - const onMessage = (event: MessageEvent) => { - const data = JSON.parse(event.data); - // サーバーから受け取ったデータを使った処理 - if (data.message_type === MessageType.Pointer) { - // aimTarget(data); - } + onMessage((data) => { + // ここも本来はPointerSchemaになる if (data.message_type === MessageType.Action) { shotTarget(data); } - }; - const currentSocketRef = socketRef?.current; - currentSocketRef?.addEventListener("message", onMessage); - return () => { - currentSocketRef?.removeEventListener("message", onMessage); - }; - }, [socketRef]); + }); + }, [onMessage]); // TODO: これらは一人用,いつかマルチプレイヤー対応する const [aim, setAim] = useState(undefined);