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

239
Vistas
Why do I have to click Submit button TWICE in order to update my useState() hook?

I am trying to create a function that redirects to a different page when it is authenticated, However, when I click onSubmit button, authenticate does not update immediately. I have to click submit twice to change authenticate from null to false/true? Why does authenticate update immediately, what should I do to solve this? Thank you

import React, {useEffect,useState} from 'react'
import Dashboard from './Dashboard'
import {useNavigate} from "react-router-dom"
import axios from 'axios'

function Register() {

    const navigate = useNavigate()
    const [username, setUsername] = useState('')
    const [password, setPassword] = useState('')
    const [authenticate, setAuthenticate] = useState(null)

    const newUser = (event) =>{
        event.preventDefault()
         axios({
            method: "POST",
            url: 'xxxxxxxxxxxxxxxxx',
            data:{
                username,
                password
            }
        }).then(res=>setAuthenticate(res.data))
        .then(()=>console.log(authenticate))
        .then(()=>authentication())

    }

    const authentication = () =>{
        authenticate ? 
            navigate("/dashboard")
           : console.log('Cannot create User')
    }


    return (
        <div>
            <form onSubmit={newUser}>
                <label>Username: </label>
                <input 
                    type="text"
                    value={username}
                    onChange={e=> setUsername(e.target.value)}
                 />
                 <br />
                 <label>Password: </label>
                 <input 
                    type="text"
                    value={password}
                    onChange={e=>setPassword(e.target.value)}
                 />
                 <br />
                 <button>Submit</button>
            </form>
            <div>
                {username}
            </div>
        </div>
    )
}

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

0

I think this is happening because, even though you called set state, it might not have been completed. This is because react batches execution of set state calls. why dont you use use effect instead to monitor the state varialbe and redirect when thwe right value is found.

const newUser = (event) =>{
        event.preventDefault()
         axios({
            method: "POST",
            url: 'xxxxxxxxxxxxxxxxx',
            data:{
                username,
                password
            }
        }).then(res=>setAuthenticate(res.data));

then create a use effect to monitor the state variable

useEffect(() => {
  if (authenticate) { //this check is required as useEffect gets executed when the component is mounted. 
   navigate("/dashboard");
  }
},[authenticate]) //have put authenticate in the dependencies of the use effect since thats what you need to monitor
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