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

155
Visualizações
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 Respostas
Responde à pergunta

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 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