Skip to content

Commit

Permalink
[@mantine/hooks] use-idle: Fix idle countdown not starting if the use…
Browse files Browse the repository at this point in the history
…r did non interact with the page (#6683)

* [@mantine/hooks] use-idle: Start timer immediately instead of waiting for an event (#6682)

* [@mantine/hooks] use-idle: Fix test formatting (#6682)

---------

Co-authored-by: Bill Parrott <[email protected]>
  • Loading branch information
chimericdream and chimericdream authored Aug 26, 2024
1 parent 4d50890 commit 95115da
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/@mantine/hooks/src/use-idle/use-idle.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,22 @@ describe('@mantine/hooks/use-idle', () => {
expect(hook.result.current).toBe(true);
});

it('Starts the timer immediately instead of waiting for the first event to happen', () => {
const spy = jest.spyOn(window, 'setTimeout');
expect(spy).not.toHaveBeenCalled();

const hook = renderHook(() =>
useIdle(1000, { initialState: false, events: ['click', 'keypress'] })
);

expect(hook.result.current).toBe(false);
expect(spy).toHaveBeenCalledTimes(1);
setTimeout(() => {
expect(hook.result.current).toBe(true);
expect(spy).toHaveBeenCalledTimes(2);
}, 1001);
});

it('Returns correct value on firing keypress event', () => {
const hook = renderHook(() => useIdle(1000));

Expand Down
5 changes: 5 additions & 0 deletions packages/@mantine/hooks/src/use-idle/use-idle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ export function useIdle(

events.forEach((event) => document.addEventListener(event, handleEvents));

// Start the timer immediately instead of waiting for the first event to happen
timer.current = window.setTimeout(() => {
setIdle(true);
}, timeout);

return () => {
events.forEach((event) => document.removeEventListener(event, handleEvents));
};
Expand Down

0 comments on commit 95115da

Please sign in to comment.