Added force update option to useNetworkedState

This commit is contained in:
Mitchell McCaffrey 2021-01-03 16:45:55 +11:00
parent d1315b3425
commit 852d5bce81
2 changed files with 14 additions and 4 deletions

View File

@ -14,9 +14,13 @@ function useNetworkedState(
// Used to control whether the state needs to be sent to the socket
const dirtyRef = useRef(false);
// Used to force a full update
const forceUpdateRef = useRef(false);
// Update dirty at the same time as state
const setState = useCallback((update, sync = true) => {
const setState = useCallback((update, sync = true, force = false) => {
dirtyRef.current = sync;
forceUpdateRef.current = force;
_setState(update);
}, []);
@ -30,7 +34,12 @@ function useNetworkedState(
useEffect(() => {
if (session.socket && dirtyRef.current) {
// If partial updates enabled, send just the changes to the socket
if (lastSyncedStateRef.current && debouncedState && partialUpdates) {
if (
lastSyncedStateRef.current &&
debouncedState &&
partialUpdates &&
!forceUpdateRef.current
) {
const changes = diff(lastSyncedStateRef.current, debouncedState);
if (changes) {
session.socket.emit(`${eventName}_update`, changes);
@ -39,6 +48,7 @@ function useNetworkedState(
session.socket.emit(eventName, debouncedState);
}
dirtyRef.current = false;
forceUpdateRef.current = false;
lastSyncedStateRef.current = debouncedState;
}
}, [session.socket, eventName, debouncedState, partialUpdates]);

View File

@ -171,7 +171,7 @@ function NetworkedMapAndTokens({ session }) {
}, [currentMap, debouncedMapState, userId, database]);
function handleMapChange(newMap, newMapState) {
setCurrentMapState(newMapState);
setCurrentMapState(newMapState, true, true);
setCurrentMap(newMap);
if (newMap && newMap.type === "file") {
@ -189,7 +189,7 @@ function NetworkedMapAndTokens({ session }) {
}
function handleMapStateChange(newMapState) {
setCurrentMapState(newMapState);
setCurrentMapState(newMapState, true, true);
}
function addMapDrawActions(actions, indexKey, actionsKey) {