ndresx / react-countdown

A customizable countdown component for React.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Countdown doesn't autoStart in React 18 functional component

musicalmacdonald opened this issue · comments

I was adapting a component from an old project to use and I noticed that the Countdown only worked when my wrapper component hot reloaded. I had to add a useEffect and manually start the countdown. Is that expected behavior? Why doesn't a change in date prop autoStart the Countdown component?

I'm using Nextjs 13.0.0 which uses react 18.2.0 and version 2.3.5 of react-countdown

Here's what I was originally using that was not working. (end is a Date string that is retrieved from an api call)

import Countdown from "react-countdown";

export const CountdownTimer = ({ end }) => {
  return (
    <div>
      <span>Live</span>
      <Countdown date={end} daysInHours />
    </div>
  );
};
export default CountdownTimer;

When you add a ref and useEffect to manually start it, it works as expected.

import Countdown from "react-countdown";
import { useEffect, useRef } from "react";

export const CountdownTimer = ({ end }) => {
 const countdownRef = useRef(null);
 
 useEffect(() => {
   if (countdownRef && countdownRef.current && end) {
     countdownRef.current.api.start();
   }
 }, [countdownRef, end]);
 
 return (
   <div>
     <span>Live</span>
     <Countdown date={end} daysInHours ref={countdownRef} />
   </div>
 );
};
export default CountdownTimer;

The countdown should start automatically once it gets mounted, as you can see here https://codesandbox.io/s/great-pine-7ezfvz.

It could have something to do with Next.js and that the countdown somehow started to run already when the page gets rendered server-side. You could try to set the key prop (e.g., the date value or something more unique once the date changes) to guarantee a new instance.

Thanks; that was my key misunderstanding. The value I'm passing to the date prop isn't defined at mount so that was the issue. Thanks for the fast response!

commented

same here ,i used next.js 13 ,react 18,

but it cannot be autostart

i add a prop key to it , then it works;

this is my code:

//  <Countdown date={Date.now() + props.time} /> this line code isn't autostart

<Countdown key={props.time} date={Date.now() + props.time} /> // this can be autostart

i don't know why, but it work now