Skip to content

useStopwatch: onClick={reset} throws TypeError: getTime is not a function #142

Description

@afnank16

Bug: reset throws TypeError: e2.getTime is not a function when used as an event handler

react-timer-hook: 4.0.6
React: 19.2.3
Browser: Microsoft Edge
OS: Windows

Description

The README demonstrates that reset can be passed directly as a React event handler:

<button onClick={reset}>Reset</button>

However, clicking the button throws:

Uncaught TypeError: e2.getTime is not a function
    at getMillisecondsFromExpiry

Steps to Reproduce

Use the exact example from the README:

import React from "react";
import { useStopwatch } from "react-timer-hook";

export default function App() {
  const {
    milliseconds,
    seconds,
    minutes,
    hours,
    days,
    isRunning,
    start,
    pause,
    reset,
  } = useStopwatch({ autoStart: true, interval: 20 });

  return (
    <>
      <div>
        {days}:{hours}:{minutes}:{seconds}:{milliseconds}
      </div>
      <button onClick={start}>Start</button>
      <button onClick={pause}>Pause</button>
      <button onClick={reset}>Reset</button>
    </>
  );
}

Expected Behavior

The stopwatch should reset to 0:0:0:0 without throwing any errors, as shown in the README.

Actual Behavior

Clicking Reset throws:

Uncaught TypeError: e2.getTime is not a function
    at getMillisecondsFromExpiry

Analysis

Looking at the bundled implementation, reset is defined as:

const reset = (offsetTimestamp, autoStart = true) => {
  const offset = offsetTimestamp
    ? getMillisecondsFromExpiry(offsetTimestamp)
    : 0;

  ...
};

and getMillisecondsFromExpiry calls:

offsetTimestamp.getTime()

When reset is passed directly as a React event handler:

<button onClick={reset} />

React invokes it as:

reset(mouseEvent);

Since mouseEvent is truthy, it is treated as an offsetTimestamp, and getMillisecondsFromExpiry(mouseEvent) eventually calls:

mouseEvent.getTime();

which results in the runtime error because MouseEvent does not implement getTime().

Workaround

Wrapping the call prevents React from passing the event object:

<button onClick={() => reset()}>
  Reset
</button>

This works correctly.

Suggestion

There seems to be a mismatch between the documentation and the implementation. Either:

  1. Update the README examples to use:
<button onClick={() => reset()}>
  Reset
</button>

or

  1. Update the implementation to ignore React's event object when reset is used directly as an event handler.

I'd appreciate it if someone could confirm whether this is an implementation bug or if the documentation needs to be updated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions