From 7a7884f38d10c36a8cb859c9cfe4f6a4605f60fd Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Tue, 5 Sep 2023 09:18:03 +0200 Subject: [PATCH] Use test seams instead of DI in useTimeoutToggle --- .eslintrc | 5 +---- src/utils/helpers/hooks.ts | 18 +++++++++++------- src/utils/services/provideServices.ts | 4 +--- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/.eslintrc b/.eslintrc index ff27eecb..06a1b38d 100644 --- a/.eslintrc +++ b/.eslintrc @@ -6,8 +6,5 @@ "parserOptions": { "project": "./tsconfig.json" }, - "ignorePatterns": ["src/service*.ts"], - "rules": { - "react-hooks/rules-of-hooks": "off" - } + "ignorePatterns": ["src/service*.ts"] } diff --git a/src/utils/helpers/hooks.ts b/src/utils/helpers/hooks.ts index 8826446a..ded2cdbc 100644 --- a/src/utils/helpers/hooks.ts +++ b/src/utils/helpers/hooks.ts @@ -1,18 +1,22 @@ import { parseQuery } from '@shlinkio/shlink-frontend-kit'; -import { useRef, useState } from 'react'; +import { useCallback, useRef, useState } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; const DEFAULT_DELAY = 2000; -export type TimeoutToggle = (initialValue?: boolean, delay?: number) => [boolean, () => void]; +export type TimeoutToggle = typeof useTimeoutToggle; export const useTimeoutToggle = ( - setTimeout: (callback: Function, timeout: number) => number, - clearTimeout: (timer: number) => void, -): TimeoutToggle => (initialValue = false, delay = DEFAULT_DELAY) => { + initialValue = false, + delay = DEFAULT_DELAY, + + // Test seams + setTimeout = window.setTimeout, + clearTimeout = window.clearTimeout, +): [boolean, () => void] => { const [flag, setFlag] = useState(initialValue); const timeout = useRef(undefined); - const callback = () => { + const callback = useCallback(() => { setFlag(!initialValue); if (timeout.current) { @@ -20,7 +24,7 @@ export const useTimeoutToggle = ( } timeout.current = setTimeout(() => setFlag(initialValue), delay); - }; + }, [clearTimeout, delay, initialValue, setTimeout]); return [flag, callback]; }; diff --git a/src/utils/services/provideServices.ts b/src/utils/services/provideServices.ts index c98e517a..404b041f 100644 --- a/src/utils/services/provideServices.ts +++ b/src/utils/services/provideServices.ts @@ -12,7 +12,5 @@ export const provideServices = (bottle: Bottle) => { bottle.constant('csvToJson', csvToJson); bottle.constant('jsonToCsv', jsonToCsv); - bottle.constant('setTimeout', window.setTimeout); - bottle.constant('clearTimeout', window.clearTimeout); - bottle.serviceFactory('useTimeoutToggle', useTimeoutToggle, 'setTimeout', 'clearTimeout'); + bottle.serviceFactory('useTimeoutToggle', () => useTimeoutToggle); };