UNPKG

@atlaskit/analytics-next

Version:

React components, HOCs and hooks to assist with tracking user activity with React components

45 lines (44 loc) 1.59 kB
import { useMemo, useRef } from 'react'; import { useAnalyticsEvents } from './useAnalyticsEvents'; export function usePatchedProps(createEventMap = {}, wrappedComponentProps) { const { createAnalyticsEvent } = useAnalyticsEvents(); const handlerCache = useRef({}); const patchedProps = useMemo(() => { const cache = handlerCache.current; // Clean up no longer used handlers in cache Object.keys(cache).filter(key => !(key in createEventMap)).forEach(key => delete cache[key]); return Object.keys(createEventMap).reduce((p, k) => { const eventCreator = createEventMap[k]; if (!['object', 'function'].includes(typeof eventCreator)) { return p; } const propValue = wrappedComponentProps[k]; if (k in cache && cache[k].eventCreator === eventCreator && cache[k].propValue === propValue) { return { ...p, [k]: cache[k].wrappedCallback }; } const wrappedCallback = (...args) => { const analyticsEvent = typeof eventCreator === 'function' ? eventCreator(createAnalyticsEvent, wrappedComponentProps) : createAnalyticsEvent(eventCreator); if (propValue && typeof propValue === 'function') { propValue(...args, analyticsEvent); } }; cache[k] = { eventCreator, wrappedCallback, propValue }; return { ...p, [k]: wrappedCallback }; }, {}); }, [createEventMap, wrappedComponentProps, createAnalyticsEvent, handlerCache]); return { patchedEventProps: patchedProps }; }