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

Improprove the design of the dropdown component using React

One of the challenges I am facing in my project is using multiple dropdowns from semantic-ui-react. Each dropdown needs to have different props, making the code look like this: <div className="wrapper"> <img className="icon" src={iconA} ...

Invoke a function in JavaScript just once using a closure

I have a JavaScript function that I want to call only once, using closure. Here's the code snippet: function initialize() { let called = 0; return function() { if (called > 0) { return } else { called++; console.log(&a ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

What is the best way to eliminate a vertical line from the canvas in react-chartjs-2?

Can someone please lend me a hand? I've been working on a project in React JS that involves using react-chartjs-2 to display charts. I'm trying to incorporate a range slider for the chart to manipulate values on the x-axis, as well as two vertic ...

There seems to be an issue with Ajax functionality within the Webix framework

Exploring webix for the first time has been quite an interesting journey. I am carefully following the guidance provided in the getting started document to create my own webix program. By placing my code in an HTML page and two JSON files as instructed, he ...

Resource loading unsuccessful: server encountered a status of 500 (Internal Server Error)

I'm struggling to figure out why I keep getting an Internal Server Error when trying to call a web service in my HTML page using JavaScript and Ajax. Here is the error message: Failed to load resource: the server responded with a status of 500 (Int ...

Managing MUI form fields using React

It seems like I may be overlooking the obvious, as I haven't come across any other posts addressing the specific issue I'm facing. My goal is to provide an end user with the ability to set a location for an object either by entering information i ...

Exploring NodeJS and ExpressJS: Unveiling the significance of routes/index.js

Can you explain the function of this particular file? Does this file handle all the GET and POST requests in a project? If so, wouldn't it become excessively long and complex for larger projects? I encountered an issue when trying to call a POST re ...

What's the best way to implement asynchronous state updating in React and Redux?

In my React incremental-style game, I have a setInterval function set up in App.ts: useEffect(() => { const loop = setInterval(() => { if (runStatus) { setTime(time + 1); } }, rate); return () => clearInterval(lo ...

Repairing the Performance of the 'Save' Feature

Can the 'Save' button in my code save team assignments for players selected using drag and drop? I'm considering using localStorage, but unsure about implementation. Note: To run the code properly, copy it as an HTML file on your computer. ...

Developing an easily optimized library using rollup to remove unnecessary code branches

I'm currently in the process of developing a component library using rollup and Vue with the goal of making it tree shakable for others who import it. The configuration setup is outlined below: Here's a snippet from package.json { "name": "re ...

Getting the x-axis points on Google charts to start at the far left point

I have integrated the Google API for charts into my application and am using multiple charts on the same page. However, I am facing an issue with setting padding for the charts. When I include more data points, the chart area occupies more space in the div ...

Dynamically scrolling using SuperScrollorama and Greensocks

I'm currently facing a JavaScript animated scroll challenge that has me scratching my head. My approach involves using the SuperScrollorama jQuery plugin, which relies on the Greensock JS tweening library. The main effect I'm aiming for is to " ...

Modifying the DOM within a getJSON callback

My current challenge involves fetching data from the YouTube API and displaying it on my website. However, I am facing an issue where the DOM changes made inside the getJSON's callback function are not reflecting on the webpage. Even though I can see ...

Oh no, there seems to be an issue with accessing the 'map' property in REACT JS. It appears to

Upon attempting to delete an item, I encountered an error message stating "cannot read notes, property of undefined". Despite this issue, the map function seems to be functioning as expected. It is my belief that there may be an error within the filter fun ...

Calculating the sum of table columns with the help of knockout.js

Is there a way to calculate the table columns using knockout.js? I am familiar with jQuery but new to knockout.js and unsure how to approach this. Instead of generating the table data using JSON, I would like to directly create it in the HTML table itself. ...

Tips for adjusting the horizontal position of a grid item within a map() loop

I am trying to align the text in my Timeline component from Material Ui always towards the center of the timeline. The TimelineContent contains Paper, Typography (for title and description), and an image. Currently, I have multiple TimelineContent element ...

The Google timezone API is displaying an inaccurate daylight saving offset

London now has an additional +1 hour of daylight saving time. I made a request to the Google timezone API for the London timezone, but unfortunately, it is not displaying the correct time. https://maps.googleapis.com/maps/api/timezone/json?location=51.507 ...

Issues with integrating chart.js in Laravel 7: Element #app not found?

Currently, I am utilizing chart.js to display the statistics of reviews and messages for a user. However, I have encountered issues with the scripts. While the stats are functioning correctly, an error message stating Cannot find element: #app is appearing ...

Leverage the controller's properties and methods within the directive

My situation involves a variety of inputs, each with specific directives: <input mask-value="ssn" validate="checkSsn"/> <input mask-value="pin" validate="checkPin"/> These properties are managed in the controller: app.controller("Ctrl", [&ap ...