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

Enhance useInterval hook to support a timeout. Add unit tests. #686

Merged
merged 3 commits into from
Dec 24, 2021
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
4 changes: 2 additions & 2 deletions app/src/features/surveys/view/SurveyObservations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,15 +133,15 @@ const SurveyObservations: React.FC<ISurveyObservationsProps> = (props) => {
});
}, [biohubApi.observation, projectId, surveyId]);

useInterval(fetchObservationSubmission, pollingTime);
useInterval(fetchObservationSubmission, pollingTime, 60000);

useEffect(() => {
if (isLoading) {
fetchObservationSubmission();
}

if (isPolling && !pollingTime) {
setPollingTime(2000);
setPollingTime(5000);
}
}, [
biohubApi,
Expand Down
101 changes: 101 additions & 0 deletions app/src/hooks/useInterval.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { render } from '@testing-library/react';
import React from 'react';
import { useInterval } from './useInterval';

interface ITestComponentProps {
callback: Function | null | undefined;
period: number | null | undefined;
timeout: number;
}

const TestComponent: React.FC<ITestComponentProps> = (props) => {
useInterval(props.callback, props.period, props.timeout);

return <></>;
};

describe('useInterval', () => {
beforeAll(() => {
jest.useFakeTimers();
});

afterAll(() => {
jest.useRealTimers();
});

it('calls the callback 5 times: once every 50 milliseconds for 250 milliseconds', async () => {
const callbackMock = jest.fn();

render(<TestComponent callback={callbackMock} period={50} timeout={250} />);

expect(callbackMock.mock.calls.length).toEqual(0); // 0 milliseconds

jest.advanceTimersByTime(49);
expect(callbackMock.mock.calls.length).toEqual(0); // 49 milliseconds

jest.advanceTimersByTime(1);
expect(callbackMock.mock.calls.length).toEqual(1); // 50 milliseconds

jest.advanceTimersByTime(49);
expect(callbackMock.mock.calls.length).toEqual(1); // 99 milliseconds

jest.advanceTimersByTime(1);
expect(callbackMock.mock.calls.length).toEqual(2); // 100 milliseconds

jest.advanceTimersByTime(50);
expect(callbackMock.mock.calls.length).toEqual(3); // 150 milliseconds

jest.advanceTimersByTime(850);
expect(callbackMock.mock.calls.length).toEqual(5); // 1000 milliseconds
});

it('stops calling the callback if the callback is updated to be falsy', async () => {
const callbackMock = jest.fn();

const { rerender } = render(<TestComponent callback={callbackMock} period={50} timeout={250} />);

expect(callbackMock.mock.calls.length).toEqual(0); // 0 milliseconds

jest.advanceTimersByTime(49);
expect(callbackMock.mock.calls.length).toEqual(0); // 49 milliseconds

jest.advanceTimersByTime(1);
expect(callbackMock.mock.calls.length).toEqual(1); // 50 milliseconds

jest.advanceTimersByTime(49);
expect(callbackMock.mock.calls.length).toEqual(1); // 99 milliseconds

jest.advanceTimersByTime(1);
expect(callbackMock.mock.calls.length).toEqual(2); // 100 milliseconds

rerender(<TestComponent callback={null} period={50} timeout={250} />);

jest.advanceTimersByTime(900);
expect(callbackMock.mock.calls.length).toEqual(2); // 1000 milliseconds
});

it('stops calling the callback if the period is updated to be falsy', async () => {
const callbackMock = jest.fn();

const { rerender } = render(<TestComponent callback={callbackMock} period={50} timeout={250} />);

expect(callbackMock.mock.calls.length).toEqual(0); // 0 milliseconds

jest.advanceTimersByTime(49);
expect(callbackMock.mock.calls.length).toEqual(0); // 49 milliseconds

jest.advanceTimersByTime(1);
expect(callbackMock.mock.calls.length).toEqual(1); // 50 milliseconds

jest.advanceTimersByTime(49);
expect(callbackMock.mock.calls.length).toEqual(1); // 99 milliseconds

jest.advanceTimersByTime(1);
expect(callbackMock.mock.calls.length).toEqual(2); // 100 milliseconds

rerender(<TestComponent callback={callbackMock} period={null} timeout={250} />);

jest.advanceTimersByTime(900);
expect(callbackMock.mock.calls.length).toEqual(2); // 1000 milliseconds
});
});
37 changes: 28 additions & 9 deletions app/src/hooks/useInterval.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,50 @@
import { useRef, useEffect } from 'react';

/**
* Runs a `callback` function on a timer, once every `delay` milliseconds.
* Runs a `callback` function on a timer, once every `period` milliseconds.
*
* Note: Does nothing if either `callback` or `delay` are null/undefined/falsy.
* Note: Does nothing if either `callback` or `period` are null/undefined/falsy.
*
* Note: If both `callback` and `delay` are valid, the `callback` function will run for the first time after `delay`
* Note: If both `callback` and `period` are valid, the `callback` function will run for the first time after `period`
* milliseconds (it will not run at time=0).
*
* @param {(Function | null | undefined)} callback the function to run at each interval. Set to a falsy value to stop
* the interval.
* @param {(number | null | undefined)} delay timer delay in milliseconds. Set to a falsy value to stop the interval.
* @param {(number | null | undefined)} period interval period in milliseconds. How often the `callback` should run.
* Set to a falsy value to stop the interval.
* @param {(number)} [timeout] timeout in milliseconds. The total polling time before the interval times out and
* automatically stops.
*/
export const useInterval = (callback: Function | null | undefined, delay: number | null | undefined): void => {
export const useInterval = (
callback: Function | null | undefined,
period: number | null | undefined,
timeout?: number
): void => {
const savedCallback = useRef(callback);

useEffect(() => {
savedCallback.current = callback;
}, [callback]);

useEffect(() => {
if (!delay || !savedCallback?.current) {
if (!period || !savedCallback?.current) {
return;
}

const timeout = setInterval(() => savedCallback?.current?.(), delay);
const interval = setInterval(() => savedCallback?.current?.(), period);

return () => clearInterval(timeout);
}, [delay]);
let intervalTimeout: NodeJS.Timeout | undefined;

if (timeout) {
intervalTimeout = setTimeout(() => clearInterval(interval), timeout);
}

return () => {
clearInterval(interval);

if (intervalTimeout) {
clearTimeout(intervalTimeout);
}
};
}, [period, timeout]);
};