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