karri jayanth
karri jayanth

Reputation: 32

If state is true than run this component

ComponentDidMount will update my component every second(with setInterval) but I want it to update only if my state is true ,is something of that sort is possible?

Upvotes: 0

Views: 45

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You could use setTimeout instead and renew timeout only if "state is true"

componentDidMount() {
  this.start()
}

componentWillUnmount() {
  this.stop()
}

start() {
  this.timeoutId = setTimeout(() => {
     doSmthUseful();

     if(state is true) { // whatever you mean by "if my state is true"
         this.start()
     }
  }, 1000)
}

stop() {
   clearTimeout(this.timeoutId)
}

Upvotes: 1

Related Questions