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

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

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