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

199
Visualizações
How can I wait a heavy function in method of React component with showing spinner?

I want to show message "calculating..." during a heavy synchronous calculation in the React Component's method.
Here is my code.
But it doesn't works. I want React to call render() both after first setState and second setState.
But React call it only after second setState.
How can I switch this.state.calculating properly?

// note: this is not async function
function myHeavyFunc() {...}

class Foo extends React.Components {
  constructor(props) {
    super(props);
    this.state = {calculating: false}
    this.handleXX = this.handleXX.bind(this);
  }

  handleXX() {
    this.setState({calculating: true}, () => { // first setState
       new Promise((resolve, reject) => {
         const x = myHeavyFunc();
         resolve(x);
       }).then(x => {
         this.setState({calculating: false}); // second setState
       });
    });
  }
  
  render() {
    const y = this.state.calculating? <p>calculating...</p> : '';
    return (
      <div>
        {y}
        <button onClick={this.handleXX}>start calc</button>
      </div>
    );
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

After finishing your calculation, you should set the "calculating" state variable back to "false" instead of "true":

handleXX() {
    this.setState({calculating: true}, () => { // first setState
        new Promise((resolve, reject) => {
            const x = myHeavyFunc();
            resolve(x);
        }).then(x => {
            this.setState({calculating: false}); // second setState
        });
    });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

This is because js is single thread.

Only in such case, you can use setTimeout to give a time to update UI to show "calculating..." and then call myHeavyFunc.

More general solution is using startTrantision which is available in React 18.

Webworker may olso solve this.

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