1

I'm attempting to build a countdown timer in React. My understanding was that componentDidMount will be called immediately after render, and so I can use it to call setState with the current time after a one second delay. Like so:

componentDidMount() {
    setTimeout(this.setState({ now: this.getTime() }), 1000)
}

However, while componentDidMount is being called (I checked with console.log), the state is not updating. How can I get componentDidMount to update the state and thus re-render the component with a new time?

Here is the full class:

class Timer extends React.Component {
    constructor() {
        super();
        this.state = {
            now: this.getTime(),
            end: this.getTime() + 180
        }
    }

    getTime() {
        return (Date.now()/1000)
    }

    formatTime() {
        let remaining = this.state.end - this.state.now
        let rawMinutes = (remaining / 60) | 0
        let rawSeconds = (remaining % 60) | 0
        let minutes = rawMinutes < 10 ? "0" + rawMinutes : rawMinutes
        let seconds = rawSeconds < 10 ? "0" + rawSeconds : rawSeconds
        let time = minutes + ":" + seconds
        return time
    }

    componentDidMount() {
        setTimeout(this.setState({ now: this.getTime() }), 1000)
    }

    render() {
        return(
            <div id="countdown">
                { this.formatTime() }
            </div>
        )
    }
}
JKiely
  • 120
  • 1
  • 2
  • 10
  • You have to pass a function to `setTimeout`. Right now you are passing the return value if `this.setState()` (which is not a function). In other words, you are calling `this.setState()` immediately on mount, not after 1000ms . – Felix Kling Dec 09 '16 at 18:44
  • 1
    Possible duplicate of [setTimeout() is not waiting](http://stackoverflow.com/q/15171266/218196) – Felix Kling Dec 09 '16 at 18:47

1 Answers1

4

first parameter of setTimeout is function - what you are passing is not a function, but its return value

to make this work you could wrap your setState with anonymous function like this:

setTimeout(() => this.setState({ now: this.getTime() }), 1000)
pwolaq
  • 6,343
  • 19
  • 45