setState outside the constructor

Asked

Viewed 31 times

0

Devs, I created a clock that updates the state every second but I have the following question, someone could explain to me why setInterval works correctly only if it is inside the constructor?

class Clock extends Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() }
    // setInterval( () => {this.setState({ date: new Date() })}, 1000)
  }
  setInterval( () => { this.setState({ date: new Date() }) }, 1000);

render() {
  return (
    <View>
      <Text style={{ fontSize: 42, textAlign: 'center' }}> {this.state.date.toLocaleTimeString()} </Text>
    </View>
  )
}
}/* CLOCK END*/

1 answer

0

Friend the setInterval() function works in the constructor due to the same being rendered when creating the component, thus calling the function. The way you passed setInterval out of render() the function is not rendered so never called so it does not execute.

To run the setInterval correctly, I advise you to put the function inside the componentWillMount according to the code below, or use Function Components and use Hook useEffect().

Code with componentWillMount.

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      counter: 0
    }
  }

  componentWillMount() {
    setInterval(() => {
      this.setState({ counter: this.state.counter + 1 })
    }, 1000)
  }

  render() {
    return (
      <View style={styles.app}>
        <Text>Contador</Text>
        <Text>{this.state.counter}</Text>
      </View>
    )
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.