Skip to content

Commit

Permalink
[@mantine/hooks] use-timeout: Add parameters for callback function (#…
Browse files Browse the repository at this point in the history
…2721)

* [@mantine/hooks] use-timout: Add  parameters for callback function

* [docs] use-timeout: Update docs with callback function parameters

* [@mantine/hooks] use-timeout: Callback parameter changed to multiple parameters

* [docs] use-timeout: Callback function with multiple parameters

* [@mantine/hooks] use-timeout: Fix tests
  • Loading branch information
linardsblk committed Oct 18, 2022
1 parent 791487e commit 19f0960
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
4 changes: 2 additions & 2 deletions docs/src/docs/hooks/use-timeout.mdx
Expand Up @@ -38,13 +38,13 @@ Return object:

```tsx
function useTimeout(
callback: () => void,
callback: (...callbackParams: any[]) => void,
delay: number,
options?: {
autoInvoke: boolean;
}
): {
start: () => void;
start: (...callbackParams: any[]) => void;
clear: () => void;
};
```
15 changes: 15 additions & 0 deletions src/mantine-hooks/src/use-timeout/use-timeout.test.ts
Expand Up @@ -88,4 +88,19 @@ describe('@mantine/hooks/use-timeout', () => {
expect(setTimeout).toHaveBeenCalled();
expect(clearTimeout).toHaveBeenCalled();
});

it('start function passes parameters to callback', () => {
const { timeout, advanceTimerToNextTick } = setupTimer(10);
const hook = renderHook(() => useTimeout(callback, timeout));

const MOCK_CALLBACK_VALUE = 'MOCK_CALLBACK_VALUE';
act(() => {
hook.result.current.start(MOCK_CALLBACK_VALUE);
});

advanceTimerToNextTick();

expect(setTimeout).toHaveBeenCalled();
expect(callback).toBeCalledWith([MOCK_CALLBACK_VALUE]);
});
});
6 changes: 3 additions & 3 deletions src/mantine-hooks/src/use-timeout/use-timeout.ts
@@ -1,16 +1,16 @@
import { useRef, useEffect } from 'react';

export function useTimeout(
fn: () => void,
callback: (...callbackParams: any[]) => void,
delay: number,
options: { autoInvoke: boolean } = { autoInvoke: false }
) {
const timeoutRef = useRef<number>(null);

const start = () => {
const start = (...callbackParams: any[]) => {
if (!timeoutRef.current) {
timeoutRef.current = window.setTimeout(() => {
fn();
callback(callbackParams);
timeoutRef.current = null;
}, delay);
}
Expand Down

0 comments on commit 19f0960

Please sign in to comment.