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

How to use getBoundingClientRect in React Odometer with React Visibility Sensor?

I need help troubleshooting an error I'm encountering while trying to implement react-odometer js with react-visibility-sensor in next js. Can anyone provide guidance on how to resolve this issue? Here is the code snippet causing the problem: https:/ ...

Enhancing Firebase Data Manipulation with Swift: Exploring the updateChildValues Function's Capabilities in Overwriting

Encountering a unique challenge when attempting to update values at different JSON branches in Firebase simultaneously. The method outlined in the documentation works well for creating new data, let key = ref.child("posts").childByAutoId().key let post ...

What is the method for sending an axios post request using the application/x-www-form-urlencoded content type?

How can I successfully send an axios post request using application/x-www-form-urlencoded? I am trying to include a refresh token in the request, but currently an empty object is being sent. However, I have verified that the token exists when checking "us ...

Axios sends back HTML content in response for Laravel and VUE integration

Within my api.php file, I have implemented two routes: Route::get('resume-list/{templateID}', 'BasicController@getAllResumes'); Route::get('resume/single/{id}', 'BasicController@getResume'); The first route is fun ...

Issue with Typescript not recognizing default properties on components

Can someone help me troubleshoot the issue I'm encountering in this code snippet: export type PackageLanguage = "de" | "en"; export interface ICookieConsentProps { language?: PackageLanguage ; } function CookieConsent({ langua ...

Transforming a jQuery menu into an active selection with Vue JS

I am looking to transition away from using jQuery and instead utilize Vue for the front end of a menu. Specifically, I need to add an active class and a 'menu-open' state to the appropriate nested list items, similar to what is achieved in the pr ...

The class name remains unchanged despite the change in value

I am currently working on a webpage that features two interactive tabs. The goal is to have one tab highlighted as "active" while the other remains inactive when clicked, and then switch roles when the other tab is selected. Below is the code snippet I ha ...

Unable to retrieve content using the query.ID in Next.js

I'm trying to figure out what is causing the issue in this code, but I can't seem to resolve it. My goal is to use the query.id inside getInitialProps to fetch some content. The fetching process works fine, but when an error occurs, I receive thi ...

Managing numerous range sliders in a Django form

My Request: I am looking to have multiple Range sliders (the number will change based on user selections) on a single page. When the sliders are moved, I want the value to be updated and displayed in a span element, as well as updating the model. The Issu ...

Next.js presents a challenge with double-language applications

I am currently in the process of developing a web application using Next.js that will cater to users who speak my native language and English. I have a specific approach in mind: First, I plan to create a folder: /pages/en-us pages/ |--(all app pages) |- ...

Mix up table data cells using Javascript/jQuery

Can anyone provide me with some helpful tips? I'm really struggling with this. My Objective I aim to create a table with two columns ("name" and "rating"), consisting of 5 rows. 2 of these rows should have a random "rating" between 6-10 2 other ro ...

Utilize D3's pie chart to showcase the data in JSON's individual collections

I am currently working on creating a pie chart that displays the distribution of collections based on their names. I have come across an issue where d3.layout.pie().value() only evaluates specified array values. Is there a solution available to extract the ...

Looking to grasp the concept of calling inline functions within a React functional component

As a newcomer to React, I recently created a new view within my company. Following the example of many guides, I have utilized inline functions and function components exclusively. One common practice I have adopted is writing onClick events in this manne ...

Organizing DIVs upon website initialization

My website features a layout with three columns: <div id="column1"></div> <div id="column2"></div> <div id="column3"></div> I currently have 3 divs on the webpage: <div id="1">aaa</div> <div id="2">b ...

The <SelectField> component in material-ui is not displaying items properly in ReactJS

I am facing an issue with Material-UI where the items are not showing up. I am trying to display categories of products in a SelectField but it doesn't seem to be working. When I click on the SelectField, no items are displayed. Below is the code for ...

Discovering a particular element involves iterating through the results returned by the findElements method in JavaScript

I am attempting to locate and interact with a specific item by comparing text from a list of items. The element distinguished by .list_of_items is a ul that consists of a list of li>a elements. I am uncertain about how to transfer the determined elemen ...

Personalizing the pop-up window using window.open

When clicking a hyperlink on a page, I need to open multiple pop-up windows. To achieve this, I must use the Window.open function instead of showModalDialog. However, I have noticed that the appearance is not satisfactory when using Window.open. (Essentia ...

The function "getElementsByClassName" in Javascript is malfunctioning

I have redesigned my website by implementing an interactive feature where users can click on a tree image to remove it and replace it with a number using JavaScript. Initially, I targeted the specific tree with the following code: document.getElementById( ...

Cross-origin request headers not permitted by the Access-Control-Allow-Headers policy in NodeJS and ExpressJS

I am currently facing an issue with my NodeJS + ExpressJS client-server setup while making API requests to a backend server. Every time I make an API request, I receive the following error: Request header field firstname is not allowed by Access-Control-A ...

Having trouble making alerts or confirmation dialogs function in JavaScript

EDIT: Many thanks to everyone who helped fix this issue (: Your help is greatly appreciated! I've been struggling to get the alert, confirm, or prompt functions to work properly in my code. Here's a snippet of the code that's causing troubl ...