amrlabib / react-timer-hook

React timer hook

Home Page:https://www.npmjs.com/package/react-timer-hook

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useStopwatch reset with offsetTimestamp always restarts at 0

yoiang opened this issue · comments

commented

Hello! I love the library, thanks so much for making it!

I'm having an issue where calling useStopwatch's reset method with an offsetTimestamp always restarts the hook at 0 (seconds, minutes, hours, days).

In my example onSeek is being called with decimal seconds, much like I am computing currentTime.

export const ExampleComponent = (props: Props): React.ReactElement => {
  const { seconds, minutes, hours, days, isRunning, start, pause, reset } = useStopwatch({
    autoStart: false,
    offsetTimestamp: 0,
  })

  const currentTime = seconds + minutes * 60 + hours * 60 * 60 + days * 60 * 60 * 24
  const setCurrentTime = (newValue: number) => {
    const preserveRunning = isRunning
    reset(newValue - currentTime, preserveRunning)
  }
 ...

  return (
      <Container
        playing={isRunning}
        onPlayingChange={(newPlayValue) => {
          if (newPlayValue) {
            start()
          } else {
            pause()
          }
        }}
        currentTime={currentTime}
        ...
        onSeek={(newValue) => {
          setCurrentTime(newValue)
        }}
      />
  )
}

Thanks in advance for your help!

Hello happy to hear that the library is helpful.

I think the problem is mainly that offsetTimestamp should be in date object format based on documentation the 2 lines below should reset the value correctly, i tested it again right now and the reset is happening with the correct offset, in the code you just shared the format is number right ? it should change to date object.

const stopwatchOffset = new Date();
stopwatchOffset.setSeconds(stopwatchOffset.getSeconds() + 300);

Apologies for the incorrect info in the readme file i will update it with correct type as the type should be date object not number

commented

Ah gotcha! Thank you for the quick response, that was the fix :)