Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
How to call setState without any triggering events?

I want to update the value of a counter variable after some fixed time indefinitely. Here is my code:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      myCount: 1    
    };
  }
  
  // Update state after every 15 seconds.
  setTimeout(function(){
     this.setState({myCount: this.state.myCount + 1});
  }, 15000);
}


However, I get error about unexpected token with this component. How can I set state within the class properly without using any event listeners?

Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your call to setTimeout is at the top level of the class body where properties, the constructor, and methods are expected. You can't put arbitrary code there. (Though you could could have a property initializer; not a good idea in this case, though.)

Put it in componentDidMount; and be sure to saved the timer handle (on the instance, usually) and clear the timer in componentWillUnmount so it doesn't fire if the component is unmounted before the timer callback occurs:

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            myCount: 1,
        };
    }

    componentDidMount() {
        // Update state after every 15 seconds.
        this.timerHandle = setTimeout(() => {                   // ****
            this.setState((previousState) => {                  // ****
                return { myCount: previousState.myCount + 1 };  // ****
            });                                                 // ****
        }, 15000);
    }

    componentWillUnmount() {
        clearTimeout(this.timerHandle);
    }
}

Side note: Notice the changes on the **** lines above

  • I replaced your traditional function with an arrow function so it closes over this.
  • I changed your callback to use the callback version of setState, which is generally best when setting state based on existing state.

...after some fixed time indefinitely.

A setTimeout callback will only occur once. You may want setInterval if you want the counter updated every 15 seconds. Or alternatively, start a new setTimeout when the callback runs, like this:

startCounterTimer() {
    // Update state after every 15 seconds.
    this.timerHandle = setTimeout(() => {
        this.setState((previousState) => {
            this.startCounterTimer(); // ***
            return { myCount: previousState.myCount + 1 };
        });
    }, 15000);
}

componentDidMount() {
    this.startCounterTimer();
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda