I am creating a login function with react and firebase, i want to call two more functions on completing signup, I tried doing
const signUpSubmit = (e,closeSignUpCard,openSignInCard) => {
e.preventDefault();
const email = e.target.email.value;
const password = e.target.password.value;
signInWithEmailAndPassword(auth, email, password)
.then(() => {
closeSignUpCard();
openSignInCard();
}
.catch((error) => {
alert(error.message);
});
};
but it shows error:
closeSignUpCard is not defined
openSignInCard is not defined
is there any other way to go about doing this? btw, i'm using firebase:^9.1.0
CodePudding user response:
You have a sequence of asynchronous tasks to be performed one after another. You need to implement/read a concept of Promise Chaining. For Example in your code:
signInWithEmailAndPassword(auth, email, password)
.then(() => {
closeSignUpCard().then(() =>{ ;
openSignInCard(); // sequence of actions
}
}
CodePudding user response:
You could turn your signUpSubmit function into an async funcion, and just await for the internal promises to end. This way you don't need to get into a callback hell and still things will happen after events you have some kind of control.
Also, if the openSignInCard
function must be executed after the closeSignUpCard
function, you can turn them into async functions and use await before they are called, so the next one will only be called after the first one ends.
Remember to be careful of using too much awaits. You know, users don't like waiting too much
const signUpSubmit = async (e, closeSignUpCard, openSignInCard) {
e.preventDefault()
const email = e.target.email.value
const password = e.target.password.value
const signIn = await signInWithEmailAndPassword(auth, email, password)
.then(r => { return { success: true } })
.catch(e => { return { success: false, error: e.message })
if ( signIn.success ){
closeSignUpCard()
openSignInCard()
} else {
alert(signIn.error)
}
}