React.js and Firebase auth: setTimeout Callback function not executed?

Viewed 141

I have a function handleSubmit that handles registering in Firebase in a react component. Inside, I want to handle errors with my setErrorTimeout function, which has a setTimeout that resets the error automatically after 3 seconds in this case..

The problem is, my Timeout is not executed, e.g the callback function inside the timeout is not being executed after 3 seconds, but everything else is.. why?

    const handleSubmit = async e => {
    e.preventDefault()

    console.log(formDetails)
 
    if (formDetails.password !== formDetails.passwordrepeat) {
        setErrorTimeout(setRegisterError, {
            message: 'Passwords do not match!',
        })
        return
    }

    console.log('Try')
    console.log(formDetails.email, formDetails.password)
    try {
        auth.createUserWithEmailAndPassword(
            formDetails.email,
            formDetails.password
        )
            .then(userCredentials => {
                if (userCredentials) {
                    const user = userCredentials.user
                    let success = user.sendEmailVerification()
                    console.log('success register:', success)
                    setRegisterSuccess(
                        'You registered successfully! please check your email!'
                    )

                    setFormDetails({})
                }
            })
            .catch(error => {
                console.log('ERROR!')
                setErrorTimeout(error)
            })
    } catch (e) {
        setErrorTimeout(e)
    }
}


const setErrorTimeout = error => {
    console.log('inside timeout!')
    setRegisterError(error)
    const timer = setTimeout(() => {
        console.log('inside cb!')
        setRegisterError(null)
    }, 3000)
    clearTimeout(timer)
    console.log('after timeout!')
}
1 Answers

You're clearing the timeout right after you create it here:

const timer = setTimeout(() => {
    console.log('inside cb!')
    setRegisterError(null)
}, 3000)
clearTimeout(timer)

You probably want that clearTimeout call to be inside the callback, although it's not even strictly needed since the timeout already fired.

Related