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

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

Merged
merged 5 commits into from Oct 18, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why fn was renamed to callback?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was called callback in docs so I thought I change it to be consistant. callback seemed more descriptive than fn to me. Feel free to comment/change if you'd like to see it reversed.

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