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

156
Vistas
State not updating in React Fetch function

I have a state, that is set to be either true or false in a fetch statement. When the fetch statement is called, the state is not updated until the second time the submit button is pressed.

It is because of that, that whenever I call an if statement right after, my code automatically navigates to my home page, thinking that the adding of a new account is successful.

When I try to set the state to null or false, the ternary statement automatically fires off as well.

I've checked the data by console logging it, and it comes back as "false" when applicable, but still never updates the state

Any insight on how to approach next?

Edit: The fetch is returning a boolean

    let navigate = useNavigate();

    // Error states
    const [successfulAdd, setSuccessfulAdd] = useState(true);


    // Function
    function handleRegister(e) {
        const user = { firstName, lastName, email, password, phone, userName, isAdmin };

        if (password !== passwordConfirm) {
            setPasswordMatch(false);
        } else {
            fetch("http://localhost:8080/user/add", {
                method: "POST",
                headers: { "Content-type": "application/json" },
                body: JSON.stringify(user),
            })
                .then(response => response.json())
                .then(data => setSuccessfulAdd(data));
        }

        if (successfulAdd) {
            navigate("../home");
        }
    }
.
.
.
    return (
.
.
.
         {/* Username Checker */}
         {successfulAdd ? "" : <div class="alert alert-danger" role="alert">
              The username you've entered has been taken
         </div>}
.
.
.
)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since Fetch API and setState are both asynchronous, you might want to put the if statement and all logic inside .then(…)

fetch(…)
 .then(res => res.json())
 .then(json => … //navigate here)
 .catch(err => … //set your error state here)

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