Skip to content

Commit

Permalink
feat(useTimeout): discovery-154 setTimeout hook (#145)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdcabrera committed Sep 20, 2022
1 parent afaa610 commit 2af7126
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"!src/components/app.js",
"!src/components/**/index.js",
"!src/common/index.js",
"!src/hooks/index.js",
"!src/redux/index.js",
"!src/redux/store.js",
"!src/redux/middleware/**",
Expand Down
8 changes: 8 additions & 0 deletions src/hooks/__tests__/__snapshots__/useTimeout.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`useTimeout should apply a hook for useTimeout: timeout 1`] = `
Object {
"cancel": [Function],
"update": undefined,
}
`;
17 changes: 17 additions & 0 deletions src/hooks/__tests__/useTimeout.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useTimeout } from '../useTimeout';

describe('useTimeout', () => {
beforeEach(() => {
jest.useFakeTimers();
});

it('should apply a hook for useTimeout', async () => {
const mockCallback = jest.fn();
const mockSetTimeout = jest.spyOn(global, 'setTimeout');
const { result } = await mountHook(() => useTimeout(mockCallback));

expect(mockSetTimeout).toHaveBeenCalledTimes(2);
expect(mockCallback).toHaveBeenCalledTimes(1);
expect(result).toMatchSnapshot('timeout');
});
});
5 changes: 5 additions & 0 deletions src/hooks/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { useTimeout } from './useTimeout';

const hooks = { useTimeout };

export { hooks as default, hooks, useTimeout };
29 changes: 29 additions & 0 deletions src/hooks/useTimeout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useEffect, useRef, useState } from 'react';
import { helpers } from '../common';

/**
* setTimeout hook
*
* @param {Function} callback
* @param {number} pollInterval
* @returns {Function}
*/
const useTimeout = (callback, pollInterval = 0) => {
const timer = useRef();
const [update, setUpdate] = useState();
const result = callback();

useEffect(() => {
if (result !== false) {
timer.current = window.setTimeout(() => setUpdate(helpers.getCurrentDate().getTime()), pollInterval);
}

return () => {
window.clearTimeout(timer.current);
};
}, [pollInterval, update, result]);

return { update, cancel: () => window.clearTimeout(timer.current) };
};

export { useTimeout as default, useTimeout };

0 comments on commit 2af7126

Please sign in to comment.