JKiely
JKiely

Reputation: 120

State not being updated in componentDidMount

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>
        )
    }
}

Upvotes: 1

Views: 588

Answers (1)

pwolaq
pwolaq

Reputation: 6381

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)

Upvotes: 4

Related Questions