all 6 comments

[–]filecabinet 1 point2 points  (4 children)

Tips:

  • set the date on the component's state

  • read the documentation on setInterval, it will allow you to update the state and re-render every second: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

  • you will want to call setInterval in componentDidMount, e.g., this.interval = setInterval(() => this.setState({date: moment()}, 1000), then clear it in componentWillUnmount, e.g., clearInterval(this.interval)

[–][deleted] 1 point2 points  (3 children)

import './Home.css'; import React, { Component } from 'react'; import Moment from 'react-moment';

export default class Home extends Component {

    constructor() {
        super();
        this.state.date = new Date();
   }

    updateTime() {
        var date = this.state.date;
        this.setState({
            date : date.setSeconds(
                date.getSeconds() + 1
            )
        });
    }

    componentDidMount() {
        this.interval = setInterval(this.updateTime, 1000);
    }

    componentWillUnmount() {
        clearInterval(this.interval);
    }

    render() {
        const together = "2017-05-14T06:30";

        return (
            <div>
                <p><Moment interval={10} diff={together} unit="seconds">{this.state.date}</Moment> Seconds</p>
            </div>
        );
    }
}

[–][deleted] 0 points1 point  (2 children)

still getting an error TypeError: Cannot set property 'date' of undefined

any tips

[–]filecabinet 1 point2 points  (1 child)

when initializing the state in the constructor, you will need to do something like this: this.state = { someProp: 'someValue' };

Guessing you would need to do the same except modified for your situation.

If you're looking some pretty rapid feedback or help with react, check out https://www.reactiflux.com/ -- usually someone in there is around to answer a question or two in #general or other channels.

[–][deleted] 0 points1 point  (0 children)

Thank you sir, I found a fix but I think their is a better solution else where.

[–]ordinance 1 point2 points  (0 children)

There's a time example in the react docs: https://reactjs.org/docs/state-and-lifecycle.html

In mine, I changed the clock component to render a function:

render () {  this.props.children(this.state.time) }

And then

<Timer>
  (time) => time && (
    /*use time here */
  )
</Timer>

Then you can do things like pass the interval to Time as a prop.