Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
¿Por qué tengo que hacer clic en el botón Enviar DOS VECES para actualizar mi gancho useState()?

Estoy tratando de crear una función que redirige a una página diferente cuando se autentica. Sin embargo, cuando hago clic en el botón onSubmit , authenticate no se actualiza de inmediato. ¿Tengo que hacer clic en enviar dos veces para cambiar authenticate de null a false/true ? ¿Por qué se authenticate la actualización inmediatamente? ¿Qué debo hacer para solucionar esto? Gracias

 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 answers
Answer question

0

Creo que esto sucede porque, aunque llamaste al estado establecido, es posible que no se haya completado. Esto se debe a que los lotes de reacción ejecutan las llamadas de estado establecido. ¿Por qué no usa el efecto de uso en su lugar para monitorear la variable de estado y redirigir cuando se encuentra el valor correcto?

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

luego crea un efecto de uso para monitorear la variable de estado

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!