Skip to content

[FSSDK-9871] Hook for track events #268

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

Merged
merged 6 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,27 @@ function MyComponent() {
```

### Tracking
Use the built-in `useTrackEvent` hook to access the `track` method of optimizely instance

Use the `withOptimizely` HoC for tracking.
```jsx
import { useTrackEvent } from '@optimizely/react-sdk';

function SignupButton() {
const [track, clientReady, didTimeout] = useTrackEvent()

const handleClick = () => {
if(clientReady) {
track('signup-clicked')
}
}

return (
<button onClick={handleClick}>Signup</button>
)
}
```

Or you can use the `withOptimizely` HoC.

```jsx
import { withOptimizely } from '@optimizely/react-sdk';
Expand Down
63 changes: 56 additions & 7 deletions src/hooks.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2022, 2023 Optimizely
* Copyright 2022, 2023, 2024 Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -18,14 +18,13 @@

import * as React from 'react';
import { act } from 'react-dom/test-utils';
import { render, screen, waitFor } from '@testing-library/react';
import { render, renderHook, screen, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import { OptimizelyProvider } from './Provider';
import { OnReadyResult, ReactSDKClient, VariableValuesObject } from './client';
import { useExperiment, useFeature, useDecision } from './hooks';
import { useExperiment, useFeature, useDecision, useTrackEvent, hooksLogger } from './hooks';
import { OptimizelyDecision } from './utils';

const defaultDecision: OptimizelyDecision = {
enabled: false,
variables: {},
Expand Down Expand Up @@ -80,7 +79,7 @@ describe('hooks', () => {
let forcedVariationUpdateCallbacks: Array<() => void>;
let decideMock: jest.Mock<OptimizelyDecision>;
let setForcedDecisionMock: jest.Mock<void>;

let hooksLoggerErrorSpy: jest.SpyInstance;
const REJECTION_REASON = 'A rejection reason you should never see in the test runner';

beforeEach(() => {
Expand All @@ -99,7 +98,6 @@ describe('hooks', () => {
);
}, timeout || mockDelay);
});

activateMock = jest.fn();
isFeatureEnabledMock = jest.fn();
featureVariables = mockFeatureVariables;
Expand All @@ -110,7 +108,7 @@ describe('hooks', () => {
forcedVariationUpdateCallbacks = [];
decideMock = jest.fn();
setForcedDecisionMock = jest.fn();

hooksLoggerErrorSpy = jest.spyOn(hooksLogger, 'error');
optimizelyMock = ({
activate: activateMock,
onReady: jest.fn().mockImplementation(config => getOnReadyPromise(config || {})),
Expand Down Expand Up @@ -141,6 +139,7 @@ describe('hooks', () => {
getForcedVariations: jest.fn().mockReturnValue({}),
decide: decideMock,
setForcedDecision: setForcedDecisionMock,
track: jest.fn(),
} as unknown) as ReactSDKClient;

mockLog = jest.fn();
Expand Down Expand Up @@ -168,6 +167,7 @@ describe('hooks', () => {
res => res.dataReadyPromise,
err => null
);
hooksLoggerErrorSpy.mockReset();
});

describe('useExperiment', () => {
Expand Down Expand Up @@ -1048,4 +1048,53 @@ describe('hooks', () => {
await waitFor(() => expect(screen.getByTestId('result')).toHaveTextContent('false|{}|true|false'));
});
});
describe('useTrackEvent', () => {
it('returns track method and false states when optimizely is not provided', () => {
const wrapper = ({ children }: { children: React.ReactNode }): React.ReactElement => {
//@ts-ignore
return <OptimizelyProvider>{children}</OptimizelyProvider>;
};
const { result } = renderHook(() => useTrackEvent(), { wrapper });
expect(result.current[0]).toBeInstanceOf(Function);
expect(result.current[1]).toBe(false);
expect(result.current[2]).toBe(false);
});

it('returns track method along with clientReady and didTimeout state when optimizely instance is provided', () => {
const wrapper = ({ children }: { children: React.ReactNode }): React.ReactElement => (
<OptimizelyProvider optimizely={optimizelyMock} isServerSide={false} timeout={10000}>
{children}
</OptimizelyProvider>
);

const { result } = renderHook(() => useTrackEvent(), { wrapper });
expect(result.current[0]).toBeInstanceOf(Function);
expect(typeof result.current[1]).toBe('boolean');
expect(typeof result.current[2]).toBe('boolean');
});

it('Log error when track method is called and optimizely instance is not provided', () => {
const wrapper = ({ children }: { children: React.ReactNode }): React.ReactElement => {
//@ts-ignore
return <OptimizelyProvider>{children}</OptimizelyProvider>;
};
const { result } = renderHook(() => useTrackEvent(), { wrapper });
result.current[0]('eventKey');
expect(hooksLogger.error).toHaveBeenCalledTimes(1);
});

it('Log error when track method is called and client is not ready', () => {
optimizelyMock.isReady = jest.fn().mockReturnValue(false);

const wrapper = ({ children }: { children: React.ReactNode }): React.ReactElement => (
<OptimizelyProvider optimizely={optimizelyMock} isServerSide={false} timeout={10000}>
{children}
</OptimizelyProvider>
);

const { result } = renderHook(() => useTrackEvent(), { wrapper });
result.current[0]('eventKey');
expect(hooksLogger.error).toHaveBeenCalledTimes(1);
});
});
});
55 changes: 54 additions & 1 deletion src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { notifier } from './notifier';
import { OptimizelyContext } from './Context';
import { areAttributesEqual, OptimizelyDecision, createFailedDecision } from './utils';

const hooksLogger = getLogger('ReactSDK');
export const hooksLogger = getLogger('ReactSDK');

enum HookType {
EXPERIMENT = 'Experiment',
Expand Down Expand Up @@ -87,6 +87,10 @@ interface UseDecision {
];
}

interface UseTrackEvent {
(): [(...args: Parameters<ReactSDKClient['track']>) => void, boolean, boolean];
}

interface DecisionInputs {
entityKey: string;
overrideUserId?: string;
Expand Down Expand Up @@ -500,3 +504,52 @@ export const useDecision: UseDecision = (flagKey, options = {}, overrides = {})

return [state.decision, state.clientReady, state.didTimeout];
};

export const useTrackEvent: UseTrackEvent = () => {
const { optimizely, isServerSide, timeout } = useContext(OptimizelyContext);
const isClientReady = !!(isServerSide || optimizely?.isReady());

const track = useCallback(
(...rest: Parameters<ReactSDKClient['track']>): void => {
if (!optimizely) {
hooksLogger.error(`Unable to track events. optimizely prop must be supplied via a parent <OptimizelyProvider>`);
return;
}
if (!isClientReady) {
hooksLogger.error(`Unable to track events. Optimizely client is not ready yet.`);
return;
}
optimizely.track(...rest);
},
[optimizely, isClientReady]
);

if (!optimizely) {
return [track, false, false];
}

const [state, setState] = useState<{
clientReady: boolean;
didTimeout: DidTimeout;
}>(() => {
return {
clientReady: isClientReady,
didTimeout: false,
};
});

useEffect(() => {
// Subscribe to initialization promise only
// 1. When client is using Sdk Key, which means the initialization will be asynchronous
// and we need to wait for the promise and update decision.
// 2. When client is using datafile only but client is not ready yet which means user
// was provided as a promise and we need to subscribe and wait for user to become available.
if (optimizely.getIsUsingSdkKey() || !isClientReady) {
subscribeToInitialization(optimizely, timeout, initState => {
setState(initState);
});
}
}, []);

return [track, state.clientReady, state.didTimeout];
};
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2018-2019, 2023 Optimizely
* Copyright 2018-2019, 2023, 2024 Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -17,7 +17,7 @@
export { OptimizelyContext, OptimizelyContextConsumer, OptimizelyContextProvider } from './Context';
export { OptimizelyProvider } from './Provider';
export { OptimizelyFeature } from './Feature';
export { useFeature, useExperiment, useDecision } from './hooks';
export { useFeature, useExperiment, useDecision, useTrackEvent } from './hooks';
export { withOptimizely, WithOptimizelyProps, WithoutOptimizelyProps } from './withOptimizely';
export { OptimizelyExperiment } from './Experiment';
export { OptimizelyVariation } from './Variation';
Expand Down
Loading