Giter Club home page Giter Club logo

react-countdown's People

Contributors

bendikjohansen avatar danilowoz avatar dependabot[bot] avatar itayganor avatar keithburgie avatar marvinschopf avatar ndresx avatar spadarshut avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-countdown's Issues

autoStart false, countdown shortly shows seconds passed before rerendering and starting properly

This issue is probably related to hooks but here goes:
My countdown is set to autostart false and to run for 60 seconds, when I start the timer, I first reset the date and key prop, otherwise the countdown would start running with the already passed seconds (e.g. if I wait 3 seconds before starting the countdown, the countdown would start at 0:57 instead of 1:00).

The parent component sets the "startTimer" prop to true, which in return sets autoStart to true as well:

useEffect(() => {
  let newCountdown = Date.now() + durationInSeconds * 1000;
  setCountdownKey(newCountdown);
  setCountdownDate(newCountdown);
}, [startTimer]);

.
.
.

<Countdown
  key={countdownKey}
  date={countdownDate}
  autoStart={startTimer}
  renderer={({ minutes, seconds }) => (
    <span>
      {minutes}:{zeroPad(seconds)}
    </span>
  )}
/>

The only issue I have right now is, once I start the countdown, it first jumps to the time passed (the same as described above with e.g. waiting 3 seconds, jumping to 0:57) and then resets correctly to 1:00 and goes down from there.

Is there a reason for the time jump with autostart false or am I not properly resetting the date and key before starting?

Countdown numbers stay static when using the now prop

We are using the now prop to change the default Date.now() so that it will always be Mountain Standard Time no matter where people are using the website. But whenever we use it, the numbers do not continue to countdown, they just stay static on the initial load up numbers. But whenever we take off the now prop, it works just fine and the numbers will continue to count down. Please help and advise if possible.

Examples fail to compile

Hello! I've been trying to use this library to build a countdown timer, as it has good documentation, and looks cool.

I've been struggling to understand how to structure a React component that wraps the Countdown component, so as to provide a method for controlling the timer, so I looked to the examples/ directory - and this file looked like the right thing.

I'm pretty new to React, and don't yet know the idioms and patterns, and this is also in Typescript - which I'm not familiar with, so eventually I checked out the repo and tried to run the examples to see if I could figure it out.

However, I get this error message after yarn install && yarn start:

Failed to compile.

/Users/miketheman/workspace/other/react-countdown/examples/node_modules/@types/react-dom/node_modules/@types/react/index.d.ts
Type error: Duplicate identifier 'LibraryManagedAttributes'.  TS2300

    2665 |         // We can't recurse forever because `type` can't be self-referential;
    2666 |         // let's assume it's reasonable to do a single React.lazy() around a single React.memo() / vice-versa
  > 2667 |         type LibraryManagedAttributes<C, P> = C extends React.MemoExoticComponent<infer T> | React.LazyExoticComponent<infer T>
         |              ^
    2668 |             ? T extends React.MemoExoticComponent<infer U> | React.LazyExoticComponent<infer U>
    2669 |                 ? ReactManagedAttributes<U, P>
    2670 |                 : ReactManagedAttributes<T, P>

I was wondering if you had seen this before, or had any idea how this might be happening?

$ which node
/usr/local/bin/node
$ node --version
v11.14.0
$ which yarn
/usr/local/bin/yarn
$ yarn --version
1.15.2

Can I use this as stopwatch timer?

I have a usecase where i want to use countdown timer and stopwatch timer in different cases.

Let me know if it is possible with this.

Countdown is not ticking when I pass date and now property.

Your help will be highly appreciated!!!!
This component is awesome. I am using date property as a enddate and Now property function which returns current date and time as per documentation. However time is not ticking down if i custom now function.
But if i use default Date.now() inside now function, Countdown start ticks...

Add zeroPadLength for days

When using countdown, zeroPadLength is not applied for days as it's described in

This option defaults to 2 in order to display the common format 00:00:00 instead of 0:0:0. If the value is higher than 2, only the hour part (never days) will be zero-padded while it stays at 2 for minutes as well as seconds.

In my case, in order to pad days as well I had to do:

const renderer = ({
    days, hours, minutes, seconds,
  }) => (
    <span>
      {zeroPad(days, 2)}:{zeroPad(hours, 2)}:{zeroPad(minutes, 2)}:{zeroPad(seconds, 2)}
    </span>
  );

It would be great if we had a param for applying zeroPad in days as well, instead of having to define a renderer function just for that.

Multiple instances of Countdown component unexpectedly share same expiration date

Hi! I've been trying to create multiple instances of countdown components in a JSX array, and I noticed that all of the rendered countdowns share the same expiration date, even if it is originally different for each one. That expiration date is every time the one of the last component in the array.

This is how I'm rendering the countdowns:

for (var auction in auctions) {
    auctionItems.push(
    <AuctionItem key={auction} auction={auctions[auction]}>
        <Countdown key={auction} date={auctions[auction].expiration_date * 1000} renderer={renderer}  />
    </AuctionItem>);
}

Any ideas of what could be going wrong?

NaN on IOS

Hi,
I am having some issues on Safari and Chrome on IOS only.
this is the output of the counter: "NaN : NaN : NaN"

Iphone 7s plus
IOS veersion 12.4

React Countdown makes Snapshot Tests Unreliable

Integrating react-countdown with react-native snapshot tests makes them finicky. Depending on test order and machine load, the snapshot happens before or after the first countdown second happens, resulting in the test being flakey.

I believe the solution would be to manage the clock for the tests, do you know an easy way to do that?

Combining custom rendered and onComplete callback breaks the countdown

Hi,

I'm using a where I have both a custom renderer and a onComplete callback as seen bellow:

<Countdown
              date={Date.now() + 5000}
              renderer={this.renderCountdown}
              onComplete={() => {
                this.setState({ isAvailable: true });
              }}
renderCountdown({ hours, minutes, seconds, completed }) {
    if (completed) {
      // Render a complete state
      return (
        <div className="countdown">
          Available <span>now!</span>
        </div>
      );
    } else {
      // Render a countdown
      return (
        <div className="countdown">
          Available in
          <span className="clock">
            {hours} hours {minutes} minutes {seconds} seconds
          </span>
        </div>
      );
    }
  }

The reason I have it like this is because I have other child components that need from that isAvailable state property, but with this combination at the end of the countdown the custom renderer will not enter the completed verification, instead will always show the clock stopped at the initial start time.

Thanks so much for any help and the super useful component!

Can I set the initial time myself?

I need to use the server's start time as a countdown, but I don't seem to have a description in the documentation.
Does the component support custom start and end times?

Years missing

Years would have been great. That's the only reason I can't use that one.

Module not found: Can't resolve 'lodash.isequal' in './node_modules/react-countdown-now/dist/Countdown.js'

After installing the module with "yarn add react-countdown-now" command, importing the Countdown component and trying "Custom & Conditional Rendering->Using a React Child for the Completed State" example I faced the following error:
./node_modules/react-countdown-now/dist/Countdown.js
Module not found: Can't resolve 'lodash.isequal' in '../node_modules/react-countdown-now/dist'

Note: installing the "lodash.isequal" package solved the issue.

Please, add to the README.md that "lodash.isequal" package needs to be installed and imported into the project.

zeroPadTime in custom renderer

i have the example of the custom renderer but the zeroPadTime is showing this format 0:0:0 while i needed to be like the following 00:00:00

const renderer = ({ hours, minutes, seconds, completed }) => {
		if (completed) { 
			// Render a complete state
			return <Completionist />;
		} else {
			// Render a countdown
			return (
				<span>
					{hours}:{minutes}:{seconds}
				</span>
			);
		}
	};

Something wrong with Safari

Hello there,
I have some problems on macOS Safari 12.1.2 @version2.1.1

renderer = ({ days, hours, minutes, seconds, completed }) => {
    console.log(days, hours, minutes, seconds, completed);
}

let startDate = new Date('2019-12-12 00:00:00');

<Countdown date={startDate} renderer={this.renderer} />

it works good on Chrome
but NaN – NaN – NaN – NaN – false on Safari

Unexpected behavior when starting countdown

Hi, I am trying to use Countdown component with autoStart set to false. I added button with onClick handler to trigger start function via refs. If event handler only contains call to start timer function, everything seem to work just fine, however if I add more logic to event handler and lets say I use this.setState({}) to modify some of my states, it starts to behave unexpectedly (countdown starts at greater time when initially set to, also it resets every time I invoke start function).
Sample code: https://codesandbox.io/s/m3nwrlw539

when restarting the timer, the countdown doesn't visibly count down

i have a component which shows an expiring token and once expired, a button is clicked to reset the expiry which resets with a new token and a new expiry time. the newer time gets passed and updates but the count down renders only the first time. i have to keep re-rendering the element to see the change in the timer's state else the countdown is stuck. if i refresh the page it works fine. do i need to restart a flag to restart its internal setTimeout or so?

thanks

Default format not working when using custom render

It looks like the default zeroPadTime format - 00:00:00:00 breaks when you use a custom date.

My code:

const renderer = ({ days, hours, minutes, seconds, completed }) => {
  if (completed) {
    // Render a completed state
    return <Completionist />;
  } else {
    // Render a countdown
    return <div className="countdown-layout"><span><div className="days">{days}</div> <div className="hours">{hours}</div>:<div className="minutes">{minutes}</div>:<div className="seconds">{seconds}</div></span></div>;
  }
};
<Countdown 
  date={new Date(1556377200000)}
  renderer={renderer}
 />

Renders as: 53 0:1:17
Would like it to be: 53 00:01:17

Typescript issue

Trying to use this in a react-create-app project and am getting the following errors popping up when trying to use it. Any ideas as to what is going on here? I see the typescript definition files in places but that doesn't seem to be making any difference...

image

Countdown resets before the end

I have a countdown that refresh a page when it's completed.
Some time before that, I show a modal.
When the modal is shown, the countdown starts again, making the refresh never happening.

Here's some parts of the code :

render() {
const renderer = ({ hours, minutes, seconds, completed }) => {
      console.log('test : ' + seconds);
      return true;
    };
return (
     <Countdown
          date={Date.now() + 15000}
          renderer={renderer}
          onTick={({ hours, minutes, seconds, completed }) => {
            if (seconds === 10) {
              this.showModal();
            }
          }}
          onComplete={() => window.location.reload()}
        />
);
  }

Any idea?

Add toggle function to the API

It would be great is besides the functions pause() and start() that the counter provides, you could also provide a toggle() function. It will be detail of luxury.

Inline styling not reflecting.

The following code is presenting the countdown without the stylization.

<Countdown className="countdown"
      date={Date.now() + 13000}
      daysInHours
      style={{color: 'red', fontWeight: 'bold',}}
    \>

No formatted fields when custom renderer

import React from "react";
import ReactDOM from "react-dom";
import Countdown from "react-countdown-now";

const renderer = props => {
  return (
    <span>
      {props.minutes}:{props.seconds}</span>
  );
};

ReactDOM.render(
  <Countdown date={Date.now() + 10000} renderer={renderer}/>,
  document.getElementById("root")
);

Displays the countdown as 0:9. Would love it to look like 00:09

@Jravvit mentioned in #35 that he managed to solve it by using props.formatted.minutes etc. But The props in the code I posted above does not have formatted field.

Countdown sometimes doesn't start

Hello,

please help me debug this issue: the countdown sometimes doesn't start (like 1 in 5 times) and stays static. Any idea what might be causing this?

Using custom renderer rest is default.

const Completionist = () =>
  (<span className="ui-highlight" style={{ backgroundColor: blueGrey[900] }}>
    Ended
  </span>);

// Renderer callback with condition
const renderer = ({ formatted: { hours, minutes, seconds }, completed }) => {
  if (completed) {
    // Render a completed state
    return <Completionist />;
  }
  // Render a countdown
  return (
    <span
      className={classnames('ui-highlight')}
      style={{ color: '#FFF', backgroundColor: lightGreen[800] }}
    >
      {minutes}:{seconds}
    </span>
  );
};

in component:

...
<Countdown date={expiry_date} renderer={renderer} />
...

Setting the controlled=true stops the countdown.

Hello, awesome job with building this nice component, I have an issue however. When I set controlled prop to true it stops the timer. Probably it's supposed to work like that, but in that case would you be able to give me an example of how the function that sets the date prop should look like? Thanks in advance.

Warning: Can only update a mounted or mounting component.

Hello. I used your package and got a warning

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.
index.js:2177
Please check the code for the Countdown component.

My usage

          <Countdown
            date={Date.now() + 5000}
            renderer={this.renderer}
            onComplete={this.redirectToLogin}
          />
  renderer({ seconds }) {
    return <span>{seconds}</span>;
  }
  redirectToLogin() {
    this.props.history.push('/Login');
  }

Warning shows after execution of redirectTo Login func.

"react": "^16.0.0"

zeroPadLength does not work with renderer function.

Hi thanks for this component, it is great!!...

I have the next problem with the zeroPadLength:

Without renderer:

Result: 1:00:03:36

With renderer (same of docs):

renderClock = ({ days, hours, minutes, seconds, completed }) => {
        if (completed) {
        // Render a completed state 
            this.forceUpdate()
        } else {
            // Render a countdown 
            return <span>{days}:{hours}:{minutes}:{seconds}</span>;
        }
}

Result: 1:0:0:36

passing parameter to onFinished causes it to fire when component is rendered

If I do the below, then onFinished fires as expected, after 2 seconds:

<Countdown targetDate={new Date(Date.now() + 2000)} interval={1000} timeSeparator={':'} format= {{ minute: 'MM', second: 'SS' }} leadingZero={true} onFinished={handleFinish} />

However, If I do this, then onFinished fires when the component is rendered, as opposed to after 2 seconds:

<Countdown targetDate={new Date(Date.now() + 2000)} interval={1000} timeSeparator={':'} format= {{ minute: 'MM', second: 'SS' }} leadingZero={true} onFinished={handleFinish(someParam} />

Using daysInHours but hours won't go over 24

Hey I tried to show countdown for approx 2 days like this for example 42:50:31 but seems like the hours part can only show it to 24 so if the hours value go past 24 it will fill days value

is this expected? since props daysInHours supposed to count days as hours

onComplete doesn't fire when tab is not focused on mobile

How can I enforce an onComplete in a scenario where a user is switching tabs/apps on mobile and then goes back after the timer has supposedly run out?
Right now the user goes back and sees 00:00 but the onComplete function wasn't executed.

big-not_fixed

use inside formik is not working as expected.

image

I'm using formik to implement form like the above, the 获取验证码 is the Countdown component, using this setup the countdown will render when ever input change blur is happened states update this is how form generally works, the problems is that the Countdown will render too much unnecessary times, and with this code below

componentDidUpdate(prevProps: CountdownProps): void {
    if (!isEqual(this.props, prevProps)) {
      this.setTimeDeltaState(this.calcTimeDelta());
    }
  }

generated error countdown time delta.

Few issues with 2.x release

I have been using v1.3.0 and updated to v2.0.3.

I've noticed few issues with the updates:

  • When countdown is completed, date parameter isn't passed in renderer prop callback. It's undefined. That wasn't the behavior on v1.3.0. It does exist when it's still counting down.
  • It says that render is a required prop. From what I can see, any of rendered, render or children can be implemented. None of those are required? And from reading the code, you can't implement renderer and children prop, for the completed state, at the same time.
    That might not be clear right away. Didn't intend to do it, just figured it might be a valid point :)

First one is easily fixed with a minor change in codebase, or at least written in breaking changes for the release when it occurred.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.