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

120
Visualizações
Changing state inside async function in React

Consider the following scenario:

const ExampleComponent = () => {

    const [status, setStatus] = useState(500)

    //Calling this function with a click event
    const submitHandler = () => {

        const url = 'localhost:8000/foo'

        fetch(url)
            .then((res) => {
                setStatus(res.status)
                return res.json()
            })
            .then((res) => {
                if (status === 200) {
                    console.log("OK")
                } else {
                    console.log("Something went wrong")
                }
            })
    }
}

In this case, since React queues the setStatus task, by the time I'm making the status === 200 check, the status has not been updated. So how do we work around such scenarios?

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

0

Of course it will print ("Something went wrong"). Because your component isn't updated yet. In order to check your answer. run this code and look at your console to find out more :

import React, { useState } from 'react';

const App = () => {

    const [status, setStatus] = useState(500);

    const submitHandler = () => {

        const url = 'https://www.irdevprogs.ir/api/tsetmc/companies'

        fetch(url)
            .then((res) => {
                setStatus(res.status)
                return res.json()
            })
            .then((res) => {
                console.log(status)
                if (status === 200) {
                    console.log("OK")
                } else {
                    console.log("Something went wrong")
                }
            })
    }


    return (
        <div>
            <button onClick={submitHandler}>first</button>
            <button onClick={()=> console.log(status)}>second</button>
        </div>
    );
};

export default App;

But what is the solution: The standard routine of the React library says that you can not setState and use the updeted state concurrent. You sholud use useEffect hook to handle this. And add the status to the dependency array to handle this case. something like this :

useEffect(() => {
          if (status === 200) {
                console.log("OK")
            } else {
                console.log("Something went wrong")
            }
     
}, [status])
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