Custom ID in Firebase Firestore is not generating a new document even after successfully creating a new user

In my Vue App, I designed a registration form to automatically create a Firestore document linked to the User UID with a unique document ID. Although the user creation process is successful, the document creation fails without showing any errors in the console even after using the catch() error method.

register() {
  //Generate pin
  function generateQuickGuid() {
    return Math.random()
      .toString(36)
      .substring(2, 15);
  }
  let ref = fs.doc(generateQuickGuid());
  ref.get().then(doc => {
    if (doc.exists) {
      console.log("Pin Exists");
    } else {
      console.log("pin doesn't exist");
      // then add user to firestore
      if (
        this.email && 
        this.password && 
        this.displayName &&
        this.category
      ) {
        auth
          .createUserWithEmailAndPassword(this.email, this.password)
          .then(cred => {
            ref
              .set({
                Name: this.displayName,
                address: "close to understanding, firebase, auth",
                phone: "09808763987",
                category: this.category,
                alias: pin,
                user_id: cred.user.uid
              })
              .catch(e => {
                console.log(e);
              });

            console.log("User Added");
          })
          .catch(error => {
            // Handle Errors here.
            var errorCode = error.code;
            var errorMessage = error.message;
            // ...
            console.log(errorCode, errorMessage);
          });
      }
    }
  });
}

Answer №1

registerUser() {
  //Creating unique pin
  function generateRandomPin() {
    return Math.random()
      .toString(36)
      .substring(2, 15);
  }
  let reference = fs.doc(generateRandomPin());
  reference.get().then(doc => {
    if (doc.exists) {
      console.log("Pin Already Exists");
    } else {
      console.log("Pin does not exist yet");
      // Adding user to firestore
      if (
        this.email &&
        this.password &&
        this.displayName &&
        this.category
      ) {
        AuthResult authResult = auth
          .createUserWithEmailAndPassword(this.email, this.password)
          .catch(error => {
            // Handling Errors
            var errorCode = error.code;
            var errorMessage = error.message;
            // Logging Error Details
            console.log(errorCode, errorMessage);
          });

       reference.set({
                Name: this.displayName,
                address: "near understanding, firebase, auth",
                phone: "09808763987",
                category: this.category,
                alias: pin,
                user_id: authResult.getUser().getUid()
              })
              .catch(e => {
                console.log(e);
              });
      }
    }
  });
}

Give this a shot!

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

Using Highstock for Dynamic Data Visualization in Web Applications

Looking to create a chart using data from a MySQL database that includes timestamps and temperature readings. The timestamp format is '2015-06-11 22:45:59' and the temperature is an integer value. Unsure if the conversion of the timestamp to Java ...

A status code of 200 indicates a successful login, which then leads to a 401 status code upon making a

Just recently, I successfully deployed a rails backend and a vue frontend to Heroku. Everything was working fine until today when I encountered a problem while trying to log in to the web app. Immediately after logging in, I started receiving 401 responses ...

What steps can I take to stop the textfield from automatically changing the ID "myid" to "myid-tokenfield" when using Tokenfield for Bootstrap?

While utilizing Tokenfield for Bootstrap, I have encountered an issue where the id of my textfield gets modified from myid to myid-tokenfield. In order to properly interact with the search engine I am using, this textfield must maintain a specific id. The ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

Determine whether a click event originated from within a child window

Currently, I am utilizing window.open to initiate a new window in javascript and my goal is to identify clicks made within the child window. Essentially, if a click event occurs in the child window, I aim to modify the parent window accordingly. I have a ...

div.load() results in a complete page reload

When I save form data, my goal is to load only the specific div without refreshing the entire page. However, despite using the preventDefault() command, the form still seems to be posting the whole page. I have tried adding the following code: $("#btn ...

I'm having trouble with my Angular application in the MEAN stack not being able to receive or read HTTP requests

error Initially, I developed an API that was capable of handling both GET and POST requests: more error const express = require('express'); const router = express.Router(); const model = require('../models/taskModel'); router.get(&ap ...

Comparison between instanceof and constructor.name

Background information: Currently, our application retrieves images from a GET API Accept: 'application/octet-stream', responseType: 'blob' and we utilize the following method to display the image on the user interface. let imageUrl ...

How come my JavaScript regular expression doesn't function properly when applied to elements in an array?

let numbers = new Array('1','2','3'); let letters = new Array('a','b','c'); let length = numbers.length; let str = 'abcdefgabcdefg'; for (let i=0; i<length; i++) { let regex = new ...

How can I modify the text color of a text element in a parent component using the child component in React Native?

Is it possible to dynamically change the text color of a text element on a parent component from a child component in React Native? I was able to achieve this with an icon in the code snippet below, but can the same be done for text? Explore More within ...

Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell. body { font-family: "Open Sans", sans-serif; line-height: 1.25; } table { border: 1px solid #ccc; border-collapse: co ...

Is jQuery failing to serialize the form data?

I have a question regarding my form. When I try to serialize it using a jQuery script, the output is empty. Could someone please assist me with this issue? Here is a snippet of my form: <form id="tabb2"> <!-- *************************** ...

Retrieval is effective in specific situations but ineffective in others

I have encountered an issue with fetching data only when using the async behavior. I am currently in the process of re-building a property booking website that was originally developed using Laravel and a self-built API. The new version is being created wi ...

Troubleshooting Vue 3 Computed Property Not Updating

I'm currently facing a challenge while developing a login form using Vue 3. I am having difficulty in getting the state to update 'realtime' or computed. When attempting to login a user from the template, the code looks like this: <button ...

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

Javascript code for creating a dropdown menu with clickable options

I have implemented a JavaScript function that creates three clickable drop-down menu buttons on my webpage. When I click on one button, the script works correctly and displays the corresponding menu. However, when I click on another button, the new menu is ...

Combining query results/objects by id in an array within a React application with Firebase Firestore

After retrieving chat messages from a Firestore snapshot, I have the following query result involving conversations among three individuals: {timestamp: "October 25th 2020, 11:13:59 am", name: "John Doe", email: "<a href="/cdn ...

The issue I'm facing is that the itemlist dialog in material-ui for React JS

Trying to create a todolist using material ui and react but encountering an issue. When a listitem is clicked, I want to open a dialog with detailed information. However, I'm having trouble closing the dialog after opening it. Here's the code sni ...

Utilize AJAX without jQuery to toggle between different content displayed on the index page and the login page

One issue I am facing is with the setup of my index.php page, which contains a sign-up form and a switch button. The button triggers an ajax request to fetch content from login.php and updates the form. However, I'm encountering difficulties when tryi ...

Executing Ajax requests to interact with a RESTful API

After developing a back end REST API using Slim Framework and closely following the REST format, I ran into an issue when working on the Front End. It seems that AJAX functions well with parameters but not paths. I am considering outsourcing or creating a ...