Home > Software engineering >  Unable to reset Time in react-countdown
Unable to reset Time in react-countdown

Time:08-27

I am using react-countdown library for counter purposes. I want to reset the timer when the time ends. It should restart again and time shound runs.

Here's the Code:

export default function App() {
  const [timerState, settimerState] = useState(Date.now()   10000);
  const onCompleteTimeFun = () => {
    console.log("Resetting Time");
    settimerState(Date.now()   10000);
  };
  const timerRenderer = ({ hours, minutes, seconds, completed }) => {
    return (
      <span>
        {hours}:{minutes}:{seconds}
      </span>
    );
  };

  return (
    <div>
      <Countdown
        date={timerState}
        onComplete={onCompleteTimeFun}
        renderer={timerRenderer}
      />
    </div>
  );
}

But its not decreasing after resetting time. I don't know what i am doing wrong. Please help me with some solutions

Here's the CodeSandBox Link: https://codesandbox.io/s/timer-app-forked-pkqfcn?file=/src/App.js

CodePudding user response:

Use the key prop in order to re-render the component. This is also stated in the docs:

This is one of React's internal component props to help identify elements throughout the reconciliation process. It can be used to restart the countdown by passing in a new string or number value.

In your case:

import Countdown from "react-countdown";

import { useState } from "react";

export default function App() {
  const [k, setK] = useState(false);
  const onCompleteTimeFun = () => {
    console.log("Resetting Time");
    setK((i) => !i);
  };
  const timerRenderer = ({ hours, minutes, seconds, completed }) => {
    return (
      <span>
        {hours}:{minutes}:{seconds}
      </span>
    );
  };

  return (
    <div>
      <Countdown
        key={k}
        date={Date.now()   10000}
        onComplete={onCompleteTimeFun}
        renderer={timerRenderer}
      />
    </div>
  );
}

Note that you don't need to save state for the date.

  • Related