简体   繁体   中英

FireBase user authentication redirect to another page

I have created a signupPage.html to authenticate a user and and log information to the realtime database in firebase using this code:

 signUp_button.addEventListener('click', (e) => {
        var email = document.getElementById('email').value;
        var password = document.getElementById('password').value;
        
        createUserWithEmailAndPassword(auth, email, password)
        
            .then((userCredential) => {
                //signed up
                const user = userCredential.user;
                
                
                //log to database
                set(ref(database, 'users/' + user.uid),{
                    email : email
                })
                //this is where page redirection
                
                alert('User Created');
            })
            
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;

                alert(errorMessage);
                
            });
    });

Then when I click my submit button everything works and the user is authenticated and information is stored into the realtime database. Now I want to redirect the user to a login page after they submit their signup. In my code under "this is where page redirection", I put location.href = "login.html". This does redirect the page and authenticate the user but it no longer stores the data into the realtime database. Any suggestions?

You were close. set() is an asynchronous action, so by adding the redirect where you were, you would redirect before the set() had the chance to execute. You must first wait for the set() to finish, and then redirect.

signUp_button.addEventListener('click', (e) => {
  const email = document.getElementById('email').value;
  const password = document.getElementById('password').value;
        
  createUserWithEmailAndPassword(auth, email, password)
    .then(async (userCredential) => {
      //signed up
      const user = userCredential.user;
                
      // log to database & wait for it to finish!
      return set(ref(database, 'users/' + user.uid), {
        email : email
      })
    })
    .then(() => {
      alert('User Created'); // avoid alert, it blocks user input!
                             // update a div with an information message instead
    
      location.href = "login.html";
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;

      alert(errorMessage);   // avoid alert, it blocks user input!
                             // update a div with an error message instead
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM