Redirecting Firebase user authentication to a different webpage

I have developed a signupPage.html to validate a user and save information to the real-time database in Firebase with the following 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);
                
            });
    });

Now, when I press my submit button, everything works fine. The user is authenticated, and their details are saved in the real-time database. However, I now want to automatically redirect the user to a login page after they submit their signup. In my code under "this is where page redirection", I placed location.href = "login.html". This change successfully redirects the page and authenticates the user, but it no longer saves the data into the real-time database. Any suggestions on how to address this?

Answer №1

Just missed it by a bit. The set() function works asynchronously, meaning that adding the redirect right after would cause the redirection to happen before the set() finishes its task. The proper sequence here is to let the set() complete first and then proceed with the 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) => {
      // User signed up successfully
      const user = userCredential.user;
                
      // Log user data into the database & wait for completion
      return set(ref(database, 'users/' + user.uid), {
        email : email
      })
    })
    .then(() => {
      alert('User Created'); 
                             // Avoid using alerts as they block user input!
                             // Consider updating a div element with an info message instead
    
      location.href = "login.html";
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;

      alert(errorMessage);
                             // Avoid using alerts as they block user input!
                             // Update a div element with an error message instead
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with Jquery toggle functionality on Firefox browser

Can anyone help me troubleshoot this jQuery script that doesn't seem to be functioning properly in Firefox? $(document).ready(function () { $('#all_lists').hide(); $('#add_lists').click( function(){ event.stopPropagation ...

Avoiding the opening of a select menu

Is there a way to prevent the dropdown menu from appearing when a select element is clicked in a form? I have attempted two methods but they did not work: $('select').click (function (e) { console.log (e); return false; }); and $(&apo ...

Utilize a display value while maintaining the v-model binding in Vue.js

Can't seem to figure this one out. I'm using Quasar Framework, but it seems like more of a Vue issue. I have a multiple-select UI component with a list of objects as options that I want to display. The v-model will bind to the currently selected ...

Embedding the view in a partial with Handlebars.js: A comprehensive guide

It might seem a bit perplexing, but allow me to explain the issue. In my NodeJs web application, I am utilizing express-handlebars. To collect user input through forms, let's consider having two distinct forms in two different views: 1) Login and 2) ...

Accurate representation of a JavaScript object using Node.js Express

I have a certain structure that I need to display on my JADE page, so I created a JSON-like object to store the data. This is how the JSON object looks like : var dataSet1 = { meta: { "name": "Some text", "minimum": mini_2, "ma ...

Tips for incorporating 'and' in the 'on' clause of 'join' in knex.js

I need assistance implementing the following SQL code in knex.js: select c.id,c.parent_id,c.comment,u.username,c.postid from comments as c join post_details as p on (p.id = c.postid and c.postid=15)join users as u on (u.id = c.userid); I attempt ...

Trouble with Google Interactive Charts failing to load after UpdatePanel refresh

Desperately seeking assistance! I have spent countless hours researching this issue but have hit a dead end. My dilemma involves using the Google Interactive Charts API within an UpdatePanel to dynamically update data based on dropdown selection changes. H ...

"Utilizing the Image onLoad event in isomorphic/universal React: Activating event registration once the image has been

When a page is rendered isomorphically, the image can be downloaded before the main script.js file. This means that the image may already be loaded before the react register's the onLoad event, resulting in the event never being triggered. script.js ...

What could be causing the 500 response code when making a request to the NextJS API route within the app directory?

Every time I attempt to access my API route, a 500 Internal Server Error code is returned The origin of the request export const fetchSuggestion = async () => { const response = await fetch('/api/getSuggestion', { cache: 'no-store&ap ...

Error message: "React Component not identified"

I am following [this React tutorial][1] and facing an issue right from the start as my React components are not being identified. Here is a snippet of my code: import React from 'react'; import {BrowserRouter as Router, Route, Routes} from "react ...

Retrieving a specific data point from the web address

What is the most efficient way to retrieve values from the window.location.href? For instance, consider this sample URL: http://localhost:3000/brand/1/brandCategory/3. The structure of the route remains consistent, with only the numbers varying based on u ...

Error: 'socket' is inaccessible before it has been initialized, specifically in the context of electron

Trying to configure an electron app where a message is sent to the server, and the server places the value on the read-only textarea. However, upon starting the app, the following error appears in the devtools console: Uncaught ReferenceError: Cannot acc ...

Is there a way to create a header that fades out or disappears when scrolling down and reappears when scrolling up?

After spending some time researching and following tutorials, I have not made much progress with my goal. The task at hand is to hide the top header of my website when the user scrolls down and then make it reappear when they scroll back up to the top of t ...

Troubleshooting problems with Chart.js scaling upon page load

Using chart.js to display a horizontal bar graph. Interestingly, upon the initial loading of the website, only a fraction of one bar is visible, and the graph fails to properly adjust to the display size until the window is manually resized. This issue per ...

The google analytics tag is failing to function properly after implementing ajax on the

I am currently utilizing Google Analytics to track all events on my website. I have noticed that when the gtag scripts are directly embedded into the HTML, everything works perfectly fine (I always verify the events in Google Analytics). However, after i ...

Saving an array within the Yii framework

The view contains the following form: <form method="POST" action="<?php echo Yii::$app->request->baseUrl;?>/telephone/addnow/" role="form" enctype="multipart/form-data"> <label>Upload your photo:</label><input type="fi ...

Using JQuery to SlideUp with a Background Color Fading Behind an Image

I'm currently utilizing JQuery slideUp/slideDown functionality to create an overlay effect on an image. This overlay is initially hidden, only appearing when the mouse hovers over the image and sliding up from the bottom. The issue I'm facing is ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...

Utilizing JSTL: Executing a function within <script> through the c:set tag in JSTL

Can someone help me with this code snippet? <c:set var="cls" value="${myFunction(param)}"/> ..... <script> function myFunction(param) { if(param == true) { return "aaa"; } else { return "bbb"; ...

Having trouble displaying image using absolute path in Express

Currently, I am developing a NodeJS application and have encountered an issue with a div element that has a background-image set in an external CSS file. Surprisingly, the CSS file functions perfectly when tested independently, and the background image dis ...