UNPKG

@azure/communication-react

Version:

React library for building modern communication user experiences utilizing Azure Communication Services

52 lines 2.24 kB
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import { CallClientContext, CallContext } from '../providers'; import { useState, useEffect, useRef, useMemo, useContext } from 'react'; /** * Hook to obtain a selector for a specified component. * * Useful when implementing a custom component that utilizes the providers * exported from this library. * * @public */ export const useSelector = (selector, selectorProps) => { var _a, _b, _c; const callClient = (_a = useContext(CallClientContext)) === null || _a === void 0 ? void 0 : _a.callClient; const callId = (_c = (_b = useContext(CallContext)) === null || _b === void 0 ? void 0 : _b.call) === null || _c === void 0 ? void 0 : _c.id; // Keeps track of whether the current component is mounted or not. If it has unmounted, make sure we do not modify the // state or it will cause React warnings in the console. https://skype.visualstudio.com/SPOOL/_workitems/edit/2453212 const mounted = useRef(false); useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }); const callIdConfigProps = useMemo(() => ({ callId }), [callId]); const [props, setProps] = useState(callClient && selector ? selector(callClient.getState(), selectorProps !== null && selectorProps !== void 0 ? selectorProps : callIdConfigProps) : undefined); const propRef = useRef(props); propRef.current = props; useEffect(() => { if (!callClient || !selector) { return; } const onStateChange = (state) => { if (!mounted.current) { return; } const newProps = selector(state, selectorProps !== null && selectorProps !== void 0 ? selectorProps : callIdConfigProps); if (propRef.current !== newProps) { setProps(newProps); } }; callClient.onStateChange(onStateChange); return () => { callClient.offStateChange(onStateChange); }; }, [callClient, selector, selectorProps, callIdConfigProps, mounted]); return selector ? props : undefined; }; //# sourceMappingURL=useSelector.js.map