//initialize auth change listener
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
router.replace('/')
}
})
setInitializing(false)
}, [])
//*handled by login button
const login = async (e: any) => {
e.preventDefault()
if (!form.email || !form.password) {
setError('Email Id and Password not found')
return
}
try {
await signInWithEmailAndPassword(auth, form.email, form.password)
const idToken = await getIdToken()
//if userId and password is wrong
//return with an error
if (!idToken) {
setError('Invalid User')
await signOut(auth)
return
}
//retrieve user data from firestore
const _getUser = await getUser(idToken!)
//if no user found
//return with an error
if (_getUser.error) {
alert(_getUser.error)
setError(_getUser.error)
await signOut(auth)
return
}
//if user is found
//store jwt token in cookie
document.cookie = `{"jwt":${_getUser.jwt}}`
} catch (e: any) {
// console.log(e.message);
}
}
Summary->
useEffect
starts the onAuthStateChanged
listener to redirect the user to the homepage if authenticated.
Login function
attempts to sign in the user with email and password using signInWithEmailAndPassword()
.
After completing necessary tasks, the function sets the document.cookie = 'boo:foo'
at the end.
Question->
The onAuthStateChanged
doesn't redirect the user to the homepage instantly after a successful sign in. Instead, it waits for the login function to complete or the document.cookie to be set. Why does this delay occur?
Framework used: NEXT JS
Language: Typescript