0

I have made a simple digital clock in React. It seems working. However, I wanted to define the callback function inside the setState() separately. But I got an error. Do you know how I can define such a function called tick() outside the componenDidMount? Below is my code

import "./Clock.css";

class Clock extends React.Component {
    state = { date: new Date() };

    componentDidMount() {
        setInterval(() => {
            this.setState({ date: new Date() });
        }, 1000);
        console.log("componentdidmount");
    }

    render() {
        return (
            <div className="clock-container">
                <h1 className="clock">{this.state.date.toLocaleTimeString()}</h1>
            </div>
        );
    }
}

export default Clock;
luckongas
  • 1,651
  • 8
  • 17
Balalayka
  • 187
  • 2
  • 15

1 Answers1

1

Is this what you want it to be like?

tick(){
    this.interval = setInterval(() => {
        this.setState({ date: new Date() });
    }, 1000);
}

componentDidMount() {
    this.tick();
    console.log('componentdidmount');
}

componentWillUnmount(){
    clearInterval(this.interval);
}
FireFighter
  • 686
  • 3
  • 6
  • Yes it works! I define a random function without content but it doesn't work: foo(){}, I got the following error: index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method – Balalayka Jan 14 '21 at 22:59
  • 1
    This is because setInterval will still be running even though the component is unmounted. In that case. you need to add a componenWillUnmount where you clear the Interval. I will edit the code and show it there. – FireFighter Jan 14 '21 at 23:04