Search code examples
reactjsreact-propsreact-statereact-lifecycle

ComponentDidMount not working and no error is displaying


class Clock extends React.Component {
state = { time: new Date().toLocaleTimeString() };
componentDidMount() {
    setInterval(() => {
        this.setState = ({ time: new Date().toLocaleTimeString()})
    }, 1000)
}
render() {
    return (
        <div className="time">
            the time is :{this.state.time}
        </div>
    );
 }
};

this is a simple clock react app where ComponentDidMount is not working


Solution

  • setState is a function, it should be invoked, not assigned. Also don't forgot to delete the timer on unmount to prevent memory leak Here is the working example

    https://codesandbox.io/s/silent-cookies-zwsog