I am trying to build a timer component such that it would tick only if a boolean isRunning variable is true. It's kind of similiar to the react basic tutorial: https://reactjs.org/docs/state-and-lifecycle.html
But for some reason my didmount function returns an error " Expected an assignment or function call and instead saw an expression".
If can someone tell me what I'm doing wrong it would be great.
Here is my code:
import React , { Component } from 'react';
class Timer extends Component {
constructor (props) {
super(props);
this.state = {
count : 0
}
}
componentDidMount() {
{
{this.props.isRunning ? this.myInterval = setInterval(() =>
{ this.tick()}, 1000) : null}
}
}
tick() {
this.setState({
count: this.state.count 1
})
}
render () {
{
var hour = Math.floor(this.state.count/3600),
minutes = Math.floor((this.state.count - hour*3600)/60),
seconds = (this.state.count - hour*3600 -minutes*60 ),
temp = new Date();
temp.setHours(hour, minutes, seconds);
}
return(
<div>
{temp.getHours()}:{temp.getMinutes()}:{temp.getSeconds()}
</div>
);
}
}
export default Timer;
I am 100% sure the problem arises due to my ComponentDidMount function.
CodePudding user response:
You are not using conditional operator properly.
This is the format : Condition ? ReturnIfTrue : ReturnIfFalse
componentDidMount() {
this.myInterval = this.props.isRunning ? setInterval(() =>
{ this.tick()}, 1000) : null
}