Home > Mobile >  Stopwatch component not taking value set in useEffect
Stopwatch component not taking value set in useEffect

Time:11-18

I have made a simple stopwatch using useStopwatch from an npm package. I want to get the starting offset in an API call on component load in the parent component and pass it to stopwatch.

I tried this:

import Stopwatch from "./Stopwatch";
import React, { useEffect, useRef, useState } from "react";

export default function App(): JSX.Element {
  const [stopwatchSecondOffset, setStopwatchSecondOffset] = useState<number | undefined>();

  useEffect(() => {
    //make api call to get offset on page load then set
    setStopwatchSecondOffset(300);
  }, []);

  return (
    <div className="App">
      <Stopwatch offset={stopwatchSecondOffset} />
    </div>
  );
}

and the stop watch component:

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

export default function Stopwatch(props: any) {
  const stopwatchOffset = new Date();
  stopwatchOffset.setSeconds(
    stopwatchOffset.getSeconds()   (props.offset ?? 0)
  );
  // stopwatchOffset.setSeconds(stopwatchOffset.getSeconds()   300);

  const {
    seconds,
    minutes,
    hours,
    days,
    isRunning,
    start,
    pause,
    reset
  } = useStopwatch({ autoStart: true, offsetTimestamp: stopwatchOffset });

  return (
    <div className={"control-buttons to-end"}>
      <div className="control-button">
        <div
          style={{ fontSize: "32px", lineHeight: "40px", marginRight: "8px" }}
        >
          <span>{hours}</span>:<span>{minutes}</span>:<span>{seconds}</span>
        </div>
      </div>
    </div>
  );
}

code sandbox: https://codesandbox.io/s/async-bash-u950t?file=/src/Stopwatch.tsx:0-850

It seems on first render the offset is null so stopwatch always starts from 0. If I pass static value in it works so I am obviously doing somethign wrong with how it renders but I can't see what.

How do I set the offset in the useEffect?

CodePudding user response:

Can't delete so posting own answer. The solution was to add conditional rendering to component:

{stopwatchSecondOffset && <Stopwatch offset={stopwatchSecondOffset} />}

CodePudding user response:

you should use dependency array in your useEffect hook .in your current code useEffect only run once and and didn'nt re render a component and not chnaging a value.

useEffect(()=>{
//your logic here
},[stopwatchSecondOffset])//[] is a dependency array add your variable which you want to get updated every time
  • Related