@fishjam-cloud/react-client
Version:
React client library for Fishjam
77 lines (76 loc) • 2.37 kB
JavaScript
import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
const eventNames = [
"socketClose",
"socketError",
"socketOpen",
"authSuccess",
"authError",
"disconnected",
"reconnectionStarted",
"reconnected",
"reconnectionRetriesLimitReached",
"joined",
"joinError",
"trackReady",
"trackAdded",
"trackRemoved",
"trackUpdated",
"peerJoined",
"peerLeft",
"peerUpdated",
"componentAdded",
"componentRemoved",
"componentUpdated",
"connectionError",
"tracksPriorityChanged",
"bandwidthEstimationChanged",
"targetTrackEncodingRequested",
"localTrackAdded",
"localTrackRemoved",
"localTrackReplaced",
"localTrackMuted",
"localTrackUnmuted",
"localTrackBandwidthSet",
"localTrackEncodingBandwidthSet",
"localTrackEncodingEnabled",
"localTrackEncodingDisabled",
"localPeerMetadataChanged",
"localTrackMetadataChanged",
"disconnectRequested",
];
/*
This is an internally used hook.
It is not meant to be used by the end user.
*/
export function useFishjamClientState(fishjamClient) {
const client = useMemo(() => fishjamClient, [fishjamClient]);
const mutationRef = useRef(false);
const subscribe = useCallback((subscribeCallback) => {
const callback = () => {
mutationRef.current = true;
subscribeCallback();
};
eventNames.forEach((eventName) => client.on(eventName, callback));
return () => {
eventNames.forEach((eventName) => client.removeListener(eventName, callback));
};
}, [client]);
const lastSnapshotRef = useRef(null);
const getSnapshot = useCallback(() => {
if (mutationRef.current || lastSnapshotRef.current === null) {
const peers = client.getRemotePeers();
const components = client.getRemoteComponents();
const localPeer = client.getLocalPeer();
const isReconnecting = client.isReconnecting();
lastSnapshotRef.current = {
peers: peers,
components,
localPeer: localPeer,
isReconnecting,
};
mutationRef.current = false;
}
return lastSnapshotRef.current;
}, [client]);
return useSyncExternalStore(subscribe, getSnapshot);
}