Sobes.tech
Junior — Senior

Creating a React component for a clock with auto-refresh

livecode

Task condition

It is necessary to adapt the code below so that the displayed time updates every second.

import React from 'react'

class Clock extends React.Component<any, any> {
  constructor(props) {
    super(props)
    this.state = { date: new Date() }
  }

  componentDidMount() {
    setInterval(
      () => this.tick(),
      1000
    )
  }

  componentWillUnmount() {
    clearInterval()
  }

  tick() {
    // @ts-ignore
    this.state.date = new Date()
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>Current time: {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    )
  }
}