Issue with Vue and Firebase: New users are being created successfully, but are being logged into existing user accounts

I've encountered a strange issue in Firebase. When I create a new user with the same password as an existing user, the new user is logged in under the previous user's account and displays all their information. However, upon logging out and signing back in with the new user's info, everything appears correctly. There was also a case where previously the new user would overwrite the existing user's path in Firebase, but that seems to be resolved now.

Below is my code snippet for creating a new user:

createNewUser () {

    // Creating a new user with email and password.

    var email = this.newUserEmail;
    var password = this.newUserPassword; 

    firebaseAuth.createUserWithEmailAndPassword(email, password).catch(function(error) {
        // Error handling.
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...
    }).then(() => {

      firebaseAuth.onAuthStateChanged(user => {
         database.ref('/users/' + user.uid).set({
             name: this.newUserName,
             email: this.newUserEmail,
             isRetailer: false,
             isAdmin: false
         });
      });  
    });

    // Redirect to home page.

    router.push({ path: '/' });

    }
  }
} 

The newly created user lands on the main home page, triggering the following code within the created() {} method:

// Checks for user and changes authentication state to true.
firebaseAuth.onAuthStateChanged(user => {
  console.log(store.state.authentication);
  console.log(user);
  store.dispatch('checkUser', user);
})

This action dispatches the following function:

 checkUser (context, user) {

    if (user.uid) {

    context.commit('authUser', user);

    // Fetching the user's isRetailer property from Firebase. 

    firebase.database()
        .ref('/users/' + user.uid + '/isRetailer/')
        .once('value').then(snapshot => context.commit('isRetailer', {
            value: snapshot.val()
        }));

        // Retrieving current user's name from Firebase and storing it in Vuex state.

        firebase.database()
            .ref('/users/' + user.uid + '/name/')
            .once('value').then(snapshot => context.commit('getDisplayName', {
                name: snapshot.val()
            }));
        } else {
            console.log('No user currently logged in');
        }
    },

In summary, I'm creating a new user in Firebase, saving their data in the database, and updating Vuex state based on retrieved data from Firebase. However, when creating a user with a completely new password, nothing happens, accompanied by a specific console error message.

Unexpectedly, logging in with a reused password results in the new user being logged into the wrong account, overwriting the existing user's details in Firebase. This perplexing issue seems to stem from not retrieving the user after account creation using a promise. Your insight on this matter would be greatly appreciated.

UPDATE: Upon further testing, signing in with my credentials triggers an overwrite of my information in Firebase with another user's data. Subsequent logins continue displaying the other user's information. A strange scenario indeed.

Thank you for your help!

Answer №1

The issue with the error message

Cannot read property 'uid' of null
occurs when Firebase returns a null value for the current user during initialization. For more information on how to manage users, please refer to the manage-users guide.

Another potential problem is that you may be navigating to a new path (e.g., home) before Firebase finishes saving the user data. It's essential to remember that this process is asynchronous in nature.


createNewUser () {

    // Create a new user with email and password.

    var email = this.newUserEmail;
    var password = this.newUserPassword; 

    firebaseAuth.createUserWithEmailAndPassword(email, password).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...
    }).then(() => {

      firebaseAuth.onAuthStateChanged(user => {
         database.ref('/users/' + user.uid).set({
             name: this.newUserName,
             email: this.newUserEmail,
             isRetailer: false,
             isAdmin: false
         }).then(()=>{
            // Once user data has been saved, navigate to the home page
            router.push({ path: '/' });
        });
      });  
    });
    }
  }
} 

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

What are the consequences of altering the DOM in React?

As a beginner react developer, I am currently working on creating a MERN App. I have a question for the community regarding my project where I needed to make several changes to the DOM as illustrated below: document.getElementsByTagName('body')[ ...

Trouble with text box focus functionality

Can someone help me focus a text box using code? Here is the code snippet: <input></input> <div id="click">Click</div> $(document).ready(function(){ $("#click").live("click", function() { var inputBox = $(this).prev(); $( ...

Reveal concealed content when a responsive table becomes scrollable on a mobile device

I recently completed a project that was overloaded with tables. I made all the tables responsive, but they still take vertical scroll if they don't fit on certain devices due to their varying widths. For instance, Table A requires vertical scroll o ...

What are the steps to implementing AJAX pagination without utilizing a database?

Is it possible to implement AJAX pagination without relying on MySQL? Can I create a PHP file containing the text and markup needed for display, and by clicking on page numbers, serve that content to the user? Can this be achieved using only jQuery and PHP ...

Updating content with jQuery based on radio button selection

Looking for assistance with a simple jQuery code that will display different content when different radio buttons are clicked. Check out the code here. This is the HTML code: <label class="radio inline"> <input id="up_radio" type="radio" n ...

Issues with npm @material-ui/core Button and TextField functionality causing errors and failures

I'm currently working on a React project and decided to incorporate the material-ui framework. After creating a component that includes a textfield and a button, I've encountered an issue where I can't interact with either of them as they s ...

How can I transfer form data to a PHP variable using an AJAX request?

Encountering some difficulties, any insights? I have included only the necessary parts of the code. Essentially, I have an HTML form where I aim to extract the value from a field before submission, trigger an ajax call, and fill in another field. It seems ...

How do I create a new JSON Object with only two properties by selecting from an existing JSON Object with four properties?

Below is a JSON object example: [ {'car':'punto','brand':'fiat','color':'black','model':'2007'}, {'car':'XUV500','brand':&ap ...

The color overlay for the class label map segmentation in AMI JS is not appearing as expected

I came across this example in vanilla JavaScript. In my project using Angular 7.3.8 with AMI version 0.32.0 (ThreeJS 0.99.0), I imported everything as an angular provider service. When trying the test examples from the provided link, I noticed that the o ...

Controller fails to initialize when utilizing $location.path or $state.go

Issue with Controller Initialization after Redirect in Ionic App I have encountered an issue where the controller is not initializing on the same page when I use $state.go or $location.href. In my Ionic app, I am using a sidemenu to pass category Id to th ...

Struggling to implement JQuery code in a Next.js application

I'm having trouble getting my tracking code to work in Next.js. <Script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments) } gtag('js', new Date()) ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

What could be the reason for my Express server returning a 404 error for all files other than index.html?

Currently, I am delving into Node.js with Express in order to set up a small server for educational purposes. Strangely, every request made to files linked within my index.html file, such as the .css, .js, and image files, results in a response code 404. ...

Tips for incorporating the "define" function into your Mocha testing

Starting my journey with JavaScript testing, I made the decision to use Mocha. The specific modules I am looking to test are AMD/RequireJS. However, it appears that Mocha only works with CommonJS modules. Consequently, when trying to run it, I encounter t ...

Abort S3 file upload using ASW-SDK

Is there a way to abort an upload without raising an error Upload aborted. when calling upload.abort()? import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage"; cons ...

Using jQuery to submit data via POST method without having the page reload

I have a link in the footer that, when clicked, jumps to the header with a # in the address bar. Is there a way to prevent this and stay in the footer? Here is the code snippet: <a href="#" class="clickIn" id="1" attrIn="Like"><span style="color ...

Error: The code is unable to access the '0' property of an undefined variable, but it is functioning properly

I am working with two arrays in my code: bookingHistory: Booking[] = []; currentBookings: any[] = []; Both arrays are populated later in the code. The bookingHistory array consists of instances of Booking, while currentBookings contains arrays of Booking ...

What is the best way to transfer a value to v-model using emit?

I'm having trouble passing the selected value from a select field to v-model. Currently, the code only seems to work with a v-text-field. <script> export default { name: 'FormSelect', props: { model ...

Determining When to Activate Button Based on Angular - Verifying That All Choices Have Been Ch

This quiz application requires the user to choose options before proceeding to the next page, with the next button being disabled by default. Once all options are chosen, the next button should become enabled. NOTE: Although the functionality for selecti ...

Having trouble sending a POST request to a nested array in Express JS

Welcome, this is my first post here so feel free to point out any missing information or incomplete details in my question :) I am currently working on a project where I need to make a POST request to an array within my data structure called features: co ...