Steps for replacing the firestore document ID with user UID in a document:

I've been attempting to retrieve the user UID instead of using the automatically generated document ID in Firebase/Firestore, but I'm encountering this error:

TypeError: firebase.auth(...).currentUser is null

This is the content of my index.js file:

// Setting up Firestore Cloud Database 
var db = firebase.firestore();
function registerUser(){
const txtname = document.getElementById('txtuname').value;
const txtEmail = document.getElementById('txtemail').value;
const txtPass = document.getElementById('txtpass').value;

firebase.auth().createUserWithEmailAndPassword(txtEmail, txtPass).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        
        if (errorCode == 'auth/weak-password') {
          alert('The password is too weak.');
        } else {
          //alert(errorMessage);
        }
        console.log(error);

      });

 var uid = firebase.auth().currentUser.uid;
if(uid !=null){
 db.collection("users").doc(uid).add({
    UserName: txtname,
    Email: txtEmail,
    Password: txtPass
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});
}

}

Answer №1

Make sure to properly handle the asynchronous nature of

firebase.auth().createUserWithEmailAndPassword(...)
.

Consider implementing the following approach:

// Connecting to Firestore Cloud Database
var db = firebase.firestore();
function registerUser(){
    const username = document.getElementById('txtuname').value;
    const email = document.getElementById('txtemail').value;
    const password = document.getElementById('txtpass').value;
    
    firebase.auth().createUserWithEmailAndPassword(email, password)
        .then(function (user) {
            // Perform operations on user creation success
        })
        .catch(function(error){
            // Handle any errors here
        });

}

Answer №2

Keep in mind that cloud functions can sometimes take an unpredictable amount of time to process. If you're looking to immediately access data stored in the users collection, this method may not be suitable for your needs.

Here's how you can use Firebase cloud functions:

exports.createUser = functions.auth.user().onCreate((user) => {
  const userMap = {
    uid: user.uid,
    email: user.email,
  };
  return admin.firestore().collection('user').doc(user.uid).set(userMap);
});

Answer №3

Utilize the example below to create your own code

In this case,

"_email","_password","_city","_phone"
represent variables

onSaved: (value) => _email = value

extracted from the TextFormField() function

Code:

String userId = await widget.auth.createUserWithEmailAndPassword(_email, _password);

print('Registered user: $userId');

final new_user = await FirebaseFirestore.instance.collection('users').doc(userId).
      set({"UserUID":'$userId',"Email":_email,"Password":_password,"City":_city,"Phone 
Number":_phone});

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

Error: undefined callback function in asynchronous parallel execution

Encountering the error message "callback is not defined" while attempting to utilize async.parallel has left me puzzled. Most examples of async.parallel demonstrate functions being inline, as shown in the async documentation here: https://caolan.github.io/ ...

Creating a structure within a stencil web component

In my current project, I am utilizing Stencil.js (typescript) and need to integrate this selectbox. Below is the code snippet: import { Component, h, JSX, Prop, Element } from '@stencil/core'; import Selectr from 'mobius1-selectr'; @ ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Having trouble retrieving the output of a database query within a NodeJs middleware

I'm currently working on retrieving the asynchronous result of a query to authenticate users. However, I am not receiving any output in my console or within the variable. I'm uncertain if it's possible to return something from a middleware. ...

Issue with Framer Motion Modal: Animation presence fails to function

Currently, I am facing an issue with the exit animation of a modal created using framer motion. While the initial animation on opening the modal works perfectly fine, the exit animation fails to trigger and the modal disappears abruptly without any transit ...

Is it possible to update the anchor to direct to the data-url attribute of the page?

In order to make my site's navigation more user-friendly, I want the page to scroll to a specific div when an a tag is clicked. This div should have a data-url attribute that matches the href of the clicked a tag. Essentially, the a tag should not nav ...

Tips for manipulating rows in HTML using jQuery when the id attribute is added

Apologies in advance for any language errors in my explanation I am working on an input table where each row has a unique ID, and the input in each row affects the next row. As new rows are added, I have implemented an incremental numbering system for the ...

Canvg | Is there a way to customize canvas elements while converting from SVG?

Recently, I encountered an issue with styling SVG graphics dynamically generated from data. The SVG graphic appears like this: https://i.sstatic.net/xvIpE.png To address the problem, I turned to Canvg in hopes of converting the SVG into an image or PDF us ...

Rotating camera independently from its parent in Three.js

I have a scenario where an Entity is traversing a CatmullRomCurve3 path, moving left with the left or down arrow keys and right with the right or up arrow keys. Initially, I encountered an issue where I wanted the Entity to face perpendicular to the path ...

Angular2 forms: creating validators for fields that are interconnected

Imagine a scenario where a form allows users to input either a city name or its latitude and longitude. The requirement is that the form must validate if the city name field is filled OR if both the latitude and longitude fields are filled, with the added ...

Is it possible to pass multiple API props to a NextJs Page at once?

I am currently facing a challenge in rendering a page that requires data from two different API fetches. The URL in the address bar appears as: http://localhost:3000/startpage?id=1 Below is the code snippet for the first API fetch: import { useRouter } f ...

javascript include new attribute adjustment

I am working with this JavaScript code snippet: <script> $('.tile').on('click', function () { $(".tile").addClass("flipOutX"); setTimeout(function(){ $(".tile-group.main").css({ marginLeft:"-40px", widt ...

Changing buffer from base64 to UTF-8 encoding in Node.js

My application imports messages from the Notes folder of Gmail using the imap npm module. When following the example on their GitHub page, all message contents are read into a buffer: stream.on('data', function(chunk) { count += chunk.len ...

Tips for retrieving all JavaScript source links from a website URL during page download

Is there a way to determine if a website is using a specific online JavaScript source, such as fontawesome? Some sources may only become apparent once they are actually loaded, rather than being visible in the website's source HTML. I attempted to us ...

When Ajax attempts to run a PHP page, it redirects me to a different page

My goal is to create a live chat feature using PHP, MySQL, and AJAX. I have almost got it working perfectly, but I'm stuck on how to submit the chat message without refreshing the page. I have a PHP page called sendchat.php that takes input data and s ...

Ways to divide a buffer in JavaScript

String was created by utilizing the toString method on the buffer. Here is a sample of the resulting string: GET / HTTP/1.1 Host: localhost:8080 Connection: keep-alive Cache-Control: max-age=0 .... Is there a way to parse this string whenever a space (" ...

Scriptmanager and Rokbox clash in a heated confrontation

I'm having trouble getting RokBox to display images on my webpage because the asp:ScriptManager seems to be causing some issues. After trying to troubleshoot, I found that when I remove the following code: <asp:ScriptManager ID="ScriptManager1" r ...

Implement jQuery to toggle a class on click for added functionality

I am attempting to create a box that changes color when clicked. When the box is first clicked, it will turn red by adding the class red, and if clicked again, it will change to blue. The colors alternate with each click, but I am unsure of how to achieve ...

Using Node.js and DIME to send binary data via POST requests

After reading a file that is 1740 bytes long into a Buffer called res, the length of res.length and res.toString('binary', 0, res.length).length is both determined to be 1740. A POST request is then sent using the request library. request.post ...

Manually adjust rotation in Three.js by clicking

I am looking to initiate an animated rotation of an object by clicking a button. I have a basic understanding that the render function operates as an infinite loop and that adding 0.1 to cylinder.rotation.x continuously rotates the object. My goal is to ...