"Simultaneously creating a Firebase user account and populating the database with user

My goal is to store new user information in my database using their unique user UID when they sign up through Firebase. Currently, my code is functioning properly, however, I am facing an issue where the name (which should be the created user UID) appears as "undefined" in my Firebase database even though the data being saved is correct.

You can view the undefined entries in my Firebase database here: https://i.stack.imgur.com/KVFBT.jpg

Below is the JavaScript code snippet I am using to save and create a new user:

// Firebase Variables
var auth = firebase.auth();

$(document).ready(function () {

  //Passing parameters from form to Firebase
  $('.addpic').on('submit', event => {
    event.preventDefault();
    const name = $('#name').val();
    const hp = $('#hp').val();
    const email = $('#email').val();
    const password = $('#password').val();
    const role = $('#role').val();

    //Firebase user authentication
    firebase.auth().createUserWithEmailAndPassword(email, password)
      .then(user => {

        // Setting data into User database
        firebase.database().ref('Admin/Person In Charge' + "/" + user.uid).set({
          Name: name,
          ContactNo: hp,
          Email: email,
          Password: password,
          Role: role
        }).then(success => {
          console.log(user);
          window.alert("Registered");
          window.location = "user.html";
        });
      })
      .catch(function (error) {

        var errorCode = error.code;
        var errorMessage = error.message;

        window.alert("Error : " + errorMessage);
      });
  });
});

I have tried various solutions to ensure that the data is saved under the UID of the created user but have not been successful. If you have any insights or suggestions, please let me know.

Answer №1

If you're wondering about the outcome of the function createUserWithEmailAndPassword, it's worth noting that it returns an instance of firebase.auth.UserCredential, rather than the actual user object itself. To access the user information, you'll need to delve one level deeper into the credential object and retrieve the user.uid.

For example:

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(userCredential => {

    // Store data in User database
    firebase.database().ref('Admin/Person In Charge' + "/" + userCredential.user.uid).set({
      Name: name,
      ContactNo: hp,
      Email: email,
      Role: role
    }).then(success => {
      console.log(user);
      window.alert("Registered");
      window.location = "user.html";
    });
  })

To understand this better in the future, consider examining the value of your user within your then block using a console.log().

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

Embedding a countdown timer in basic HTML code

Attempting to embed the following into an HTML website: The issue I am facing is that when I run it, the timer does not appear. However, when I run it in fsFiddle, I do see the countdown timer. What could be causing this problem? <!DOCTYPE html> & ...

Incorporate an HTTP Header into a Wicket Ajax Request

I am trying to include a custom HTTP header in all Ajax (XHR) requests made by Wicket. I attempted the following: $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('X-My-Header', 'value'); } }); and $(doc ...

Is there a way to dynamically change the title of a tab when new content is added to a minimized page?

Is anyone familiar with how websites like Facebook and Buzzfeed update their tab titles when there are multiple tabs open? I have noticed that sometimes they add a "(1)" or "(2)" to indicate changes on the page. Do they use JavaScript to achieve this eff ...

Why is this specific element showing as undefined in the form during editing, but appearing correctly in both the debugger and console.log?

I've encountered an error that keeps popping up: "Cannot read property 'textContent' of undefined at HTMLDocument". This error specifically occurs when dogName, dogBreed, and dogSex are set within the 'click' listener. It's st ...

Switching between different Vaadin tabs using client-side technology

I am currently working on a project to enhance the navigation experience on a website. To achieve this, I am creating a Silverlight component that will enable users to switch between tabs in a Tabsheet. While exploring the functionalities, I came across an ...

The background image shifts dynamically with a parallax effect as the page is scrolled

I need help solving a parallax issue that I'm currently facing. On my webpage, I have a background image positioned at the top with a parallax effect achieved through background-position: fixed. However, I now require the image to scroll along with t ...

The pre tag does not have any effect when added after the onload event

I have been experimenting with a jQuery plugin for drawing arrows, detailed in this article. When using the plugin, this code is transformed: <pre class="arrows-and-boxes"> (Src) > (Target) </pre> into this format: Src --> Target The ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

Python Scrapy: Extracting live data from dynamic websites

I am attempting to extract data from . The tasks I want to accomplish are as follows: - Choose "Dentist" from the dropdown menu at the top of the page - Click on the search button - Observe that the information at the bottom of the page changes dynamica ...

Is there a way to modify the colors of particles in GPUParticleSystem with Three.js?

I have encountered an issue where I am trying to add black particles in a white THREE.scene. Despite changing the spawn option color, there are still white particles present as if there is a base particle spawn color. The problem arises when I set a white ...

Div element to animate and vanish in a flash

I'm attempting to create a smooth slide effect for a div element before it disappears. Below is the code I am currently using: function slideLeft(element) { $("#" + element).animate({ left: "510" }, { duration: 750 }); document.getEle ...

Changing the color gradient of a range column chart in ApexCharts

Currently, I am working on a project where I am trying to incorporate a waterfall chart using ApexCharts. Unfortunately, the Waterfall chart is not readily available with ApexCharts, so I am experimenting with modifying the range column chart into a Waterf ...

Top tips for seamless image transitions

Currently working on a slideshow project and aiming to incorporate smooth subpixel image transitions that involve sliding and resizing, similar to the Ken Burns effect. After researching various techniques used by others, I am curious to learn which ones ...

a guide on integrating dynamic text input in AngularJS with SVG circles created in D3.js for effective filtering

I am working with a d3js bubble chart that contains multiple circles, each identified by an id corresponding to a city name. var cities = ["Toronto", "London", "Paris"]; In addition, there is a standard input box in the HTML code. <input id="searchBo ...

Is it possible for using str_replace('<') to protect against code injected by users?

Recently, I've been working on a script that involves user input. In this script, I use echo str_replace('<', '&lt;', str_replace('&','&amp;',$_POST['input']));. It seemed like a solid f ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Is there a way to automatically convert a webpage to a PDF when it is requested?

I'm looking to convert the webpage into a PDF file upon request. Below are the scripts I am using: <script> pdfdoc.fromHTML($('#container').html(), 10, 10, { 'width': 110, ...

I am unable to enter any text in an angular modal

Currently, I am facing an issue where I am unable to click on the search input field within a modal. The goal is to implement a search functionality in a table displayed inside a modal window. The idea is to have a list of hospitals where users can view d ...

Why is it that a JSX element can take a method with parentheses or without as its child?

Why is it that when I attempt to pass a method without parentheses into a React component as a child of one of the JSX elements, an error appears in the console? However, simply adding parentheses resolves the issue. What's the deal? For example: ran ...

Looping through a JSON object to create a table showcasing public holidays

Currently, I am working on creating a table that lists all the public holidays. The table comprises rows with holiday names on the left and dates on the right. Unfortunately, the table only displays data from the final array of the JSON object, whereas I ...