0

The idea: I want to display time after login and hide it after logout. Program works, but after logout I get warning (look image 3). So, I wonder: will warning affect app, and if yes, how to solve this issue.

Here's Clock.jsx:

import React from 'react'

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

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

    componentWillMount() {
        clearInterval(this.timerID)
    }

    tick() {
        this.setState({
            date: new Date()
        })
    }

    render() {
        return (
            <div>
                <hr />
                <p>Current Time: </p>
                <p>{this.state.date.toLocaleTimeString()}.</p>
                <hr />
            </div>
        )
    }
}

Calling that component in index.jsx:

function Logout(props) {
    return (        
        <div>
            <button className="btn btn-danger" onClick={props.onClick}>
                Logout
            </button>
            <Clock />
        </div>
    )
}

Image 1 - Login:

image 1

Image 2 - After login:

image 2

Image 3 - Warning after logout:

image 3

BlackB0ne
  • 135
  • 1
  • 10

2 Answers2

0

Try calling clearInterval in componentWillUnmount. This insures that the setState method written inside tick is not called when your Clock component is not available in DOM.

Ishan Trivid
  • 101
  • 3
0

In Clock.jsx I made a mistake typing componentWillMount() instead of componentWillUnmount().

Old code fragment:

componentWillMount() {
    clearInterval(this.timerID)
}

Fixed:

componentWillUnmount() {
    clearInterval(this.timerID)
}
BlackB0ne
  • 135
  • 1
  • 10