Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda