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

260
Visualizações
In React useEffect, how do you sneak state updates in between long running code?

I'm having trouble getting my loading status to appear before the longRunningCode executes. I tried making it async to no avail.

const [loadingStatus, setLoadingStatus] = useState(undefined);
const [myAction, setMyAction] = useState(undefined);

const longRunningCode = () => {
  const file = // synchronous code to generate a gzipped File object
  return file;
}

// also tried
// const longRunningCode = async () => {
// ...

useEffect(() => {
  if (myAction) {
    setLoadingStatus('Do the thing...')
    const result = longRunningCode()
    // also tried `await` with async version
    // ...
    setLoadingStatus(undefined)
    setMyAction(undefined)
  }
}, [myAction])

//...

return (
  <div>
    <p>{loadingStatus}</p>
    <button onClick={() => setMyAction({})}>Generate file</button>
  </div>
)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I was thinking something along the lines of:

const [loadingStatus, setLoadingStatus] = useState(undefined);
const [myAction, setMyAction] = useState(undefined);
const longRunningCode = () => {
 return new Promise(resolve, reject)=>{
  const file = // synchronous code to generate a File object
  resolve(file);
 }
}

useEffect(() => {
  if (myAction) {
    setLoadingStatus('Do the thing...')
    longRunningCode().then(file=>{
      // ...
      setLoadingStatus(undefined)
      setMyAction(undefined)
    })
  }
}, [myAction])

//...

return <p>{loadingStatus}</p><button onClick={() => setMyAction({})} />

**Edit: ** with setTimeout

const [loadingStatus, setLoadingStatus] = useState(undefined);
const [myAction, setMyAction] = useState(undefined);
const longRunningCode = () => {
  const file = // synchronous code to generate a File object
  return file
 }
}

useEffect(() => {
  if (myAction) {
    setLoadingStatus('Do the thing...')
     
     //a 0 second delay timer waiting for longrunningcode to finish
     let timer = setTimeout(() =>{
      longRunningCode()
      setLoadingStatus(undefined)
      setMyAction(undefined)
     }, 0);
      // clear Timmer on unmount
      return () => {
        clearTimeout(timer);
      };
    
  }
}, [myAction])

//...

return <p>{loadingStatus}</p><button onClick={() => setMyAction({})} />
about 4 years ago · Juan Pablo Isaza Relatório

0

useEffect callbacks are only allowed to return undefined or a destructor function. In your example, you have passed an async function which returns a Promise. It may or may not run, but you will see React warnings that useEffect callbacks are run synchronously.

Instead, define an async function, and then call it.

const [loadingStatus, setLoadingStatus] = useState(undefined);
const [myAction, setMyAction] = useState(undefined);

useEffect(() => {
  const doAction = async () => {
    if (myAction) {
      setLoadingStatus('Do the thing...');
      const result = await longRunningCode();
      // ...
      setLoadingStatus(undefined);
      setMyAction(undefined);
    }
  };

  doAction();
}, [myAction]);

//...

return <p>{loadingStatus}</p><button onClick={() => setMyAction({})} />

Otherwise, what you have written will work.

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