Home > Enterprise >  wait for setstate to execute a function react
wait for setstate to execute a function react

Time:08-15

im trying to handle a login, but the problem is that when i click the log in button the function that handle the login makes faster than the setState, so i have to click 2 times to enter the next page, im want to know if theres a way to wait for the setState to finish and then call handleLogin(), i try to use useEffect but executes 1 time always and i dont want that

const [validationState, setValidationState] = useState()
const [credentials, setCredentials] = useState({})
let navigate = useNavigate()

const handleLogIn = () => {
    console.log(credentials)
    userValidation(credentials)
    .then((response) => {
        console.log(response)
        setValidationState(response)
    })
}
useEffect(() => {
    if (validationState) {
        localStorage.setItem('islogged', true)
        navigate('/database-filler')
    }else{
        localStorage.setItem('islogged', false)
    }
},[validationState,navigate])

const handleSubmitLogIn = (event) =>{ 
    event.preventDefault()
    const [username,password] =document.forms[0]
    setCredentials({.    //this makes faster than the handleLogin function
        'user' : username.value, 
        'password' : password.value
    })
    handleLogIn()
    
}

CodePudding user response:

we got this solution with a partner, i think is better to make this than use a state

 const [validationState, setValidationState] = useState()

let navigate = useNavigate()

const handleLogIn = ({user,  password}) => {
    userValidation({user, password})
    .then((response) => {
        console.log(response)
        setValidationState(response)
    })
}
useEffect(() => {
    if (validationState) {
        localStorage.setItem('islogged', true)
        navigate('/database-filler')
    }else{
        localStorage.setItem('islogged', false)
    }
},[validationState,navigate])

const handleSubmitLogIn = async (event) =>{ 
    event.preventDefault()
    const [username,password] =document.forms[0]
    handleLogIn({
        'user' : username.value, 
        'password' : password.value
    })
}

CodePudding user response:

that's how the setState function works it's not sync you can use this workaround

const handleSubmitLogIn = (event) =>{ 
    event.preventDefault()
    const [username,password] =document.forms[0]
    setCredentials({.    function
        'user' : username.value, 
        'password' : password.value
    })
    handleLogIn(user,password)//send as a parameter

another solution would be using useEffect

CodePudding user response:

There is no point in saving username and password after the user has clicked login in a slice of state, atleast not one I can see....

Create a slice of state for each formValue, update them when the formValue changes, and in the login function you check for those slices of state.

  • Related