Files
grungnet/src/hooks/useNetworkedState.js

116 lines
3.5 KiB
JavaScript
Raw Normal View History

2021-01-01 13:06:56 +11:00
import { useEffect, useState, useRef, useCallback } from "react";
2021-01-01 13:06:56 +11:00
import useDebounce from "./useDebounce";
import { diff, applyChanges } from "../helpers/diff";
2021-01-01 13:06:56 +11:00
/**
* @callback setNetworkedState
* @param {any} update The updated state or a state function passed into setState
* @param {boolean} sync Whether to sync the update with the session
* @param {boolean} force Whether to force a full update, usefull when partialUpdates is enabled
*/
/**
* Helper to sync a react state to a `Session`
*
* @param {any} initialState
* @param {Session} session `Session` instance
* @param {string} eventName Name of the event to send to the session
* @param {number} debounceRate Amount to debounce before sending to the session (ms)
* @param {boolean} partialUpdates Allow sending of partial updates to the session
* @param {string} partialUpdatesKey Key to lookup in the state to identify a partial update
*
* @returns {[any, setNetworkedState]}
*/
2021-01-01 13:06:56 +11:00
function useNetworkedState(
initialState,
2021-01-01 13:06:56 +11:00
session,
eventName,
2021-01-22 06:01:43 +11:00
debounceRate = 500,
partialUpdates = true,
partialUpdatesKey = "id"
2021-01-01 13:06:56 +11:00
) {
const [state, _setState] = useState(initialState);
// Used to control whether the state needs to be sent to the socket
2021-01-01 13:06:56 +11:00
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, force = false) => {
2021-01-01 13:06:56 +11:00
dirtyRef.current = sync;
forceUpdateRef.current = force;
2021-01-01 13:25:19 +11:00
_setState(update);
2020-12-31 17:56:51 +11:00
}, []);
2021-01-01 13:06:56 +11:00
const eventNameRef = useRef(eventName);
useEffect(() => {
eventNameRef.current = eventName;
}, [eventName]);
const debouncedState = useDebounce(state, debounceRate);
const lastSyncedStateRef = useRef();
useEffect(() => {
2021-01-01 13:06:56 +11:00
if (session.socket && dirtyRef.current) {
// If partial updates enabled, send just the changes to the socket
if (
lastSyncedStateRef.current &&
debouncedState &&
partialUpdates &&
!forceUpdateRef.current
) {
const changes = diff(lastSyncedStateRef.current, debouncedState);
if (changes) {
const update = { id: debouncedState[partialUpdatesKey], changes };
session.socket.emit(`${eventName}_update`, update);
}
} else {
session.socket.emit(eventName, debouncedState);
}
2021-01-01 13:06:56 +11:00
dirtyRef.current = false;
forceUpdateRef.current = false;
lastSyncedStateRef.current = debouncedState;
}
}, [
session.socket,
eventName,
debouncedState,
partialUpdates,
partialUpdatesKey,
]);
useEffect(() => {
function handleSocketEvent(data) {
_setState(data);
lastSyncedStateRef.current = data;
}
function handleSocketUpdateEvent(update) {
_setState((prevState) => {
if (prevState && prevState[partialUpdatesKey] === update.id) {
let newState = { ...prevState };
applyChanges(newState, update.changes);
if (lastSyncedStateRef.current) {
applyChanges(lastSyncedStateRef.current, update.changes);
}
return newState;
} else {
return prevState;
}
});
}
session.socket?.on(eventName, handleSocketEvent);
session.socket?.on(`${eventName}_update`, handleSocketUpdateEvent);
return () => {
session.socket?.off(eventName, handleSocketEvent);
session.socket?.off(`${eventName}_update`, handleSocketUpdateEvent);
};
}, [session.socket, eventName, partialUpdatesKey]);
return [state, setState];
}
export default useNetworkedState;