Kamilski81
Kamilski81

Reputation: 15107

How can I reference the originally created hook in React?

I have the following usage of my hook, but it doesn't use the new timerDuration when I update inside my input:

 const [secondsBetweenRepsSetting, setSecondsBetweenRepsSetting] = useState(DEFAULT_SECONDS_BETWEEN_REPS)

 const {secondsLeft, isRunning, start, stop} = useTimer({
        duration: secondsBetweenRepsSetting,
        onExpire: () => sayRandomExerciseName(),
        onTick: () => handleTick(),
    });

 const onTimeBetweenRepsChange = (event: any) => {
        const secondsBetweenRepsSettingString = event.target.value;
        const secondsBetweenRepsSettingInt = parseInt(secondsBetweenRepsSettingString)
        setSecondsBetweenRepsSetting(secondsBetweenRepsSettingInt)
    }

 return <React.Fragment>
   <input type="number" name="secondsBetweenRepsSetting" value={secondsBetweenRepsSetting} onChange={onTimeBetweenRepsChange}/>
 </React.Fragment>

And here is the implementation of the useTimer hook, which I'm not sure why it's not getting my duration update?

import { useState } from 'react';
import Validate from "../utils/Validate";
import useInterval from "./useInterval";

export default function useTimer({ duration: timerDuration, onExpire, onTick}) {
  const [duration] = useState(timerDuration)
  const [secondsLeft, setSecondsLeft] = useState(timerDuration)
  const [isRunning, setIsRunning] = useState(false)

  function start() {
    setIsRunning(true)
  }
  function stop() {
    setIsRunning(false)
  }

  function handleExpire() {
    Validate.onExpire(onExpire) && onExpire();
  }

  useInterval(() => {
    const secondsMinusOne = secondsLeft - 1;
    setSecondsLeft(secondsMinusOne)
    if(secondsMinusOne <= 0) {
      setSecondsLeft(duration) // Reset timer automatically
      handleExpire()
    } else {
      Validate.onTick(onTick) && onTick();
    }
  }, isRunning ? 1000 : null)

  return {secondsLeft, isRunning, start, stop, }
}

Upvotes: 0

Views: 50

Answers (1)

Nick Carbone
Nick Carbone

Reputation: 218

Remove the line: const [duration] = useState(timerDuration);

You are already getting duration from timerDuration, just use that.

Upvotes: 1

Related Questions