UNPKG

@azure/communication-react

Version:

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

50 lines 2.15 kB
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import { ChatClientContext } from '../providers/ChatClientProvider'; import { useState, useEffect, useRef, useMemo, useContext } from 'react'; import { ChatThreadClientContext } from '../providers/ChatThreadClientProvider'; /** * 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; const chatClient = useContext(ChatClientContext); const threadId = (_a = useContext(ChatThreadClientContext)) === null || _a === void 0 ? void 0 : _a.threadId; // 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 threadConfigProps = useMemo(() => ({ threadId }), [threadId]); const [props, setProps] = useState(chatClient && selector ? selector(chatClient.getState(), selectorProps !== null && selectorProps !== void 0 ? selectorProps : threadConfigProps) : undefined); const propRef = useRef(props); propRef.current = props; useEffect(() => { if (!chatClient || !selector) { return; } const onStateChange = (state) => { const newProps = selector(state, selectorProps !== null && selectorProps !== void 0 ? selectorProps : threadConfigProps); if (propRef.current !== newProps) { setProps(newProps); } }; chatClient.onStateChange(onStateChange); return () => { chatClient.offStateChange(onStateChange); }; }, [chatClient, selector, selectorProps, threadConfigProps]); return (selector ? props : undefined); }; //# sourceMappingURL=useSelector.js.map