Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand useTracking API to accept contextual data #168

Merged
merged 18 commits into from
Nov 11, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 73 additions & 1 deletion src/__tests__/hooks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,78 @@ describe('hooks', () => {
expect(innerRenderCount).toEqual(1);
});

it('does not cause unnecessary dispatches due to object literals passed to useTracking', () => {
let dispatchCount = 0;

const App = () => {
const [state, setState] = React.useState({});

useTracking(
{},
{
dispatchOnMount: () => {
dispatchCount += 1;
},
}
);
bgergen marked this conversation as resolved.
Show resolved Hide resolved

return (
<div className="App">
<h1>
Extra dispatches caused by new object literals passed on re-render
</h1>
<button
onClick={() => setState({ count: state.count + 1 })}
type="button"
>
Update trackingData and options objects
</button>
</div>
);
};

const wrapper = mount(<App />);

wrapper.find('button').simulate('click');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe click it a couple times and wrap in act() for good measure? Would be great to also assert that the state is actually updated to confirm.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great call on this. Adding a couple extra clicks exposed a bug. I decided not to wrap the clicks in act() because it wasn't making a difference in the result, and it turns out that's because as of React 16.8, if we use mount, enzyme wraps calls to .simulate in act for us. I think we just needed it in the other spot to handle the asynchronicity.

I still want to do some manual testing again before we merge this just to be sure everything is working properly. Should we aim for a Monday merge?


expect(dispatchCount).toEqual(1);
});

it('dispatches the correct data if props change', () => {
const App = props => {
const { trackEvent } = useTracking(
{ data: props.data || '' },
{
dispatch,
dispatchOnMount: true,
}
);

const handleClick = () => {
trackEvent({ event: 'click' });
};

return (
<div className="App">
<button onClick={handleClick} type="button" />
</div>
);
};

const wrapper = mount(<App />);

expect(dispatch).toHaveBeenCalledWith({ data: '' });

wrapper.setProps({ data: 'Updated data prop' });
wrapper.find('button').simulate('click');

expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenLastCalledWith({
event: 'click',
data: 'Updated data prop',
});
});

it('can interop with the HoC (where HoC is top-level)', () => {
const mockDispatchTrackingEvent = jest.fn();
const testData1 = { key: { x: 1, y: 1 }, topLevel: 'hoc' };
Expand Down Expand Up @@ -702,7 +774,7 @@ describe('hooks', () => {
});
});

it('can interop with HoC (where Hook is top-level', () => {
it('can interop with HoC (where Hook is top-level)', () => {
const mockDispatchTrackingEvent = jest.fn();
const testData1 = { key: { x: 1, y: 1 }, topLevel: 'hook' };
const testData2 = { key: { x: 2, z: 2 }, page: 'TestDeepMerge' };
Expand Down
26 changes: 18 additions & 8 deletions src/useTrackingImpl.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
import { useCallback, useContext, useEffect, useMemo } from 'react';
import { useCallback, useContext, useEffect, useMemo, useRef } from 'react';
import merge from 'deepmerge';

import ReactTrackingContext from './ReactTrackingContext';
import dispatchTrackingEvent from './dispatchTrackingEvent';

export default function useTrackingImpl(
trackingData = {},
{ dispatch = dispatchTrackingEvent, dispatchOnMount = false, process } = {}
) {
export default function useTrackingImpl(trackingData, options) {
const { tracking } = useContext(ReactTrackingContext);
const latestData = useRef(trackingData);
const latestOptions = useRef(options);

useEffect(() => {
// store the latest data & options in a mutable ref to prevent
// dependencies from changing when the consumer passes in non-memoized objects
// same approach that we use for props in withTrackingComponentDecorator
latestData.current = trackingData;
latestOptions.current = options;
});

const { dispatch = dispatchTrackingEvent, dispatchOnMount = false, process } =
latestOptions.current || {};

const getProcessFn = useCallback(() => tracking && tracking.process, [
tracking,
]);

const getOwnTrackingData = useCallback(() => {
const ownTrackingData =
typeof trackingData === 'function' ? trackingData() : trackingData;
const data = latestData.current;
const ownTrackingData = typeof data === 'function' ? data() : data;
return ownTrackingData || {};
}, [trackingData]);
}, []);

const getTrackingDataFn = useCallback(() => {
const contextGetTrackingData =
Expand Down