Leveraging the power of Firebase and JavaScript to easily include custom user fields during the user

UPDATE: I encountered an issue while using Nextjs framework. However, it works perfectly fine when I use a vanilla CRA (Create React App). It appears that the problem is somehow related to Nextjs.

I'm currently working on creating a new user document to store additional user information whenever a new user is registered. I have a function in place that first creates a new user and then attempts to populate a new document in my users collection.

Although the user is successfully created, the users collection doesn't get populated with the new user document containing the extra information.

const createUser = (user) => {

  fire.auth()
    .createUserWithEmailAndPassword(user.email, user.password)
    .then((registeredUser) => {
      // Displays the ID of the newly created user.
      console.log(registeredUser.user.uid);
      fire.firestore().collection('users')
        .add({
          uid: registeredUser.user.uid,
          firstName: user.firstName,
          lastName: user.lastName,
        }).catch((err) => {
          // No errors are being thrown here.
          console.log(err);
        });
    });
};

However, by including

fire.firestore().collection('users').add({});

I end up with two new documents saved in my users collection - one empty object from the 'dummy' line and the other with the additional user information.

const createUser = (user) => {
  // When I include this line, both the empty object and the additional user info
  // are stored in the database.
  fire.firestore().collection('users').add({});

  fire.auth()
    .createUserWithEmailAndPassword(user.email, user.password)
    .then((registeredUser) => {
      // provides me with the ID of the newly registered user.
      console.log(registeredUser.user.uid);
      fire.firestore().collection('users')
        .add({
          uid: registeredUser.user.uid,
          firstName: user.firstName,
          lastName: user.lastName,
        }).catch((err) => {
          // No errors occur here.
          console.log(err);
        });
    });
};

Can someone offer insight into why this behavior occurs? Why does the initial block of code not function as expected? How can I adjust the initial block of code to ensure that my additional user fields are correctly stored in the database?

Your assistance would be greatly appreciated.

Sincerely, Stephan Valois

Answer №1

It's rather puzzling why you feel the need to include this line to insert an empty document:

fire.firestore().collection('users').add({});

In my opinion, it serves no purpose and I would recommend removing it altogether.

Furthermore, I strongly advise using the user's UID as the document ID instead of relying on the random ID generated by add(). This approach will simplify locating the document in the future, especially when provided only with the user's UID:

fire.firestore().collection('users').doc(registeredUser.user.uid).set({
    uid: registeredUser.user.uid,
    firstName: user.firstName,
    lastName: user.lastName,
})

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

Learn the process of eliminating a class utilizing this JavaScript function

This script is designed to identify and manipulate elements with the class menu-option-set. When an element within this class is clicked, it adds the class "selected" to that specific element while removing it from all others in the list. My goal is to en ...

Verification - enter a unique key for each ajax call

As I develop a new app, I am aiming to separate the HTML/JS layer from the PHP layer in order to prepare for a potential phonegap version in the future. One major concern I have is regarding authentication. Since I won't be able to rely on session va ...

How can parameters be included in ng-href when using ng-click?

So I have this list of products and I want to pass the current product id when clicking on ng-href by using a function with ng-click in the ng-href. This is what my html file looks like: <div class="agile_top_brands_grids" ng-model="products" ng-repe ...

Create a Vue component that utilizes the v-for directive to iterate through a list of items, passing data from a

Imagine having two arrays with a similar structure like this: const individuals = [{name: "Jane Doe", id: "0001"},{name: "John Doe", id:"0002"}, {name: "Sam Smith", id: "0003"}, {name: "Joe ...

Javascript - readjust weight distribution accordingly when a weight is removed

I am in possession of a dataset that shows the proportion of each test contributing to the final grade. In cases where a student has missed one or more tests, the weight is redistributed accordingly among the tests they did take. I want to determine how ...

The Vue framework patiently anticipates the arrival of data from props before proceeding with

I am facing a recurring problem where I need to retrieve data from a prop before performing certain actions within the created hook. This leads to errors such as "this.value is not defined" because the prop data has not yet loaded. To remedy this, I have ...

Is it possible to obtain a return value from Electron's webContents.executeJavaScript when NodeIntegration is disabled?

Is there a way to retrieve a return value without using NodeIntegration in Electron, similar to ipcRenderer when it's enabled? ...

Discover a step-by-step guide on incorporating a swipe animation into a responsive carousel

I'm currently using next JS in combination with tailwind css and the react-responsive-carousel package. The issue I'm facing is that when I swipe through the images, they transition horizontally without any additional effects such as fade or ease ...

Transform a PNG image with transparency into a JPEG file using imagemagick

Consider utilizing the imagemagick npm module for your image manipulation needs. In the task of converting a .png file with a transparent background to a .jpeg with a white background, you may encounter challenges. Here is an example: const ImageMagick ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

What is the best way to send extra information to getserversideprops in Next.js from a separate page?

To successfully transfer the projectID from the previous page(/projects) to the destination page (/project/[projectName]), I need to execute an API endpoint request containing the projectID in order to retrieve specific project details. What would be the ...

Steps to successfully implement a Formik NextJS POST request

Here is the relevant code segment: const handleSubmit = async (event, values, actions) => { event.preventDefault(); axios.post(url, payload(values.name)) .then(res => { // do something }).catch(err => { ...

Unable to invoke a custom hook within another custom hook in a React application

I've developed a React application using create-react-app. Currently, I'm working on creating a custom hook that integrates with the Microsoft Authentication Library (MSAL). MSAL provides a custom React hook that I want to utilize within my own ...

The most lightweight scraper for individual website pages

There is a certain website that constantly updates its data. Unfortunately, there is no API available to access this information programmatically in JavaScript, which presents a common challenge for me. To tackle this issue, I have created a simple JavaSc ...

Resetting the Countdown Clock: A Transformation Process

I have implemented a countdown timer script that I found online and made some adjustments to fit my website's needs. While the current setup effectively counts down to a specific date and time, I now require the timer to reset back to a 24-hour countd ...

Is it possible to use a webcam to scan a QR code directly into a webpage?

Is it possible to enable users to input data on a webpage using QR code scanning? I'm unsure if there is a tool that can be integrated into the page or paired with a library to make this happen, or if I need to consider an external solution beyond th ...

Encountering a NextJS pre-render issue while generating the sitemap.xml

While developing my markdown-based blog, everything functioned smoothly in the developer environment. However, when I attempted to build the project using the command npm run build, I encountered an error related to pre-rendering failure. Error occurred pr ...

The error message "Error: Node.js heap out of memory" occurred while running the npm build command in NestJS

I'm encountering a problem with my Nest js API. While everything works perfectly when I build it locally and can start the development server without any issues, I face difficulties building or starting the server when deploying to my hosting server. ...

Using JQuery Datatables to output HTML based on JavaScript conditional logic

I am presently working on a project that involves using JQuery Datatables to display my data. Within this project, I am utilizing the datatables render method to format the data before it is displayed. However, I have encountered a challenge where I need t ...

Creating an array using Vue.js

When I initialize a Vue data array like this [0: Object, 2: Object];, the console log in Vue shows the array as [0: Object, 1: undefined 2: Object];. This causes issues when iterating through with 'v-for="cell in row.cells"' as it results in tryi ...