Moved to socket for game state networking

This commit is contained in:
Mitchell McCaffrey
2020-12-05 17:16:06 +11:00
parent 2847118ac1
commit f2cb8b69db
4 changed files with 71 additions and 115 deletions

View File

@@ -0,0 +1,24 @@
import { useEffect, useState, useRef } from "react";
function useNetworkedState(defaultState, session, eventName) {
const [state, _setState] = useState(defaultState);
// Used to control whether the state needs to be sent to the socket
const dirtyRef = useRef(false);
// Update dirty at the same time as state
function setState(update, sync = true) {
dirtyRef.current = sync;
_setState(update);
}
useEffect(() => {
if (dirtyRef.current) {
session.socket.emit(eventName, state);
dirtyRef.current = false;
}
}, [state, eventName]);
return [state, setState];
}
export default useNetworkedState;