score:3

change your tick function to this:

tick = () => {
  var timestamp = this.state.datetimestamp + 1;
  this.setstate({
    datetimestamp: timestamp,
    dateformatted: moment(timestamp).tostring()
  });
}

this is because from docs :

setstate() does not immediately mutate this.state but creates a pending state transition. accessing this.state after calling this method can potentially return the existing value.

therefore in your next setstate call it use old value. my proposition change this two values at once.

score:8

@krzysztofsztompka is correct, but i would add that maintaining two separate state variables to represent the current date as a number and as a formatted string is an antipattern. derived state variables (i.e., state variables that can be calculated using another state variable) increases the responsibility on the developer to always keep the two state variables in sync. that may not seem too difficult in this simple example, but it can become more difficult in larger, more complicated components/apps. instead, it is generally considered better practice to maintain one source of truth and calculate any derived values on the fly as you need them. here's how i would apply this pattern to your example.

import react from 'react';
import moment from 'moment';

export default class clock extends react.component {

  constructor(props) {
    super(props);
    this.state = {
      datetimestamp : date.now()
    };
    this.tick = this.tick.bind(this);
  }

  tick() {
    this.setstate({
      datetimestamp: this.state.datetimestamp + 1
    });
  }

  componentdidmount() {
    this.interval = setinterval(this.tick, 1000);
  }

  componentwillunmount() {
    clearinterval(this.interval);
  }

  render() {
    // calculate the formatted date on the fly
    const date = moment(this.state.datetimestamp).tostring();
    return(
      <div classname="clock"> heure locale : {date}</div>
    );
  }

}

Related Query

More Query from same tag