0

I'm using this package called react-countdown-now I have many items I'm just wondering why all the items counting down same time

https://codesandbox.io/s/4rpn84j5m0

As you can see below in my example the new item rest the old item

import React, { Component } from 'react';
import { render } from 'react-dom';
import Countdown from 'react-countdown-now';

class App extends Component {
  constructor() {
    super();
    this.state = {
      show: false
    };
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({ show: true })
    }, 2500)
  }

  render() {
    return (
      <div>
      
        <Countdown date={Date.now() + 10000} /><br />
        {this.state.show ? <Countdown date={Date.now() + 10000} /> : <span>waiting new item....</span>}
        <p>
        Why the new item rest the old item?
        </p>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

Why the new item rest the old item?

1 Answer 1

1

The reason is because the expression Date.now() + 10000 gets recalculated on every re-render / state update. You need to store the dates somewhere.

As an example:

https://codesandbox.io/s/zq1mv4zmz4

import React, { Component } from "react";
import { render } from "react-dom";
import Countdown from "react-countdown-now";

class App extends Component {
  constructor() {
    super();

    this.state = {
      dates: [Date.now() + 10000]
    };
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({ show: true });
    }, 2500);
  }

  render() {
    return (
      <div>
        {this.state.dates.map(date => (
          <div>
            <Countdown date={date} />
          </div>
        ))}
        <button onClick={() => this.addDate()}>New Item</button>
        <p>Why the new item rest the old item?</p>
      </div>
    );
  }

  addDate() {
    let dates = [...this.state.dates, Date.now() + 10000];
    this.setState({ dates });
  }
}

render(<App />, document.getElementById("root"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.