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

Cypress, encountering issues with If/Else or Switch Case implementations

My current challenge involves adding else if / switch case in my test. The issue I am facing is that when the initial 'if' condition fails, it does not go into the else if statement. This problem persists in both else if statements and switch cas ...

How can I prevent the browser's back button from functioning on an AngularJS webpage?

Is there a way to disable the browser's back button and refresh button in Angular? For example, in my source code: Page Source: "use strict"; .controller("wizardSecondController", function($scope, $state, $stateParams, wizardManager) { $scope.$on ...

When working with React-Native App and combining React-Navigation with Redux, a common error may occur stating that 'action.routeName' is not an object. This issue can be

I encountered an error in my React Native app while implementing react-navigation within redux. The issue, along with a screenshot for reference, can be found here. Currently, I have not incorporated any redirects into the application. However, my plan in ...

Setting a menu item as active in a SvelteKit app: A step-by-step guide

I encountered an issue with the main navigation menu in my sveltekit application. The problem is that when the app is loaded or refreshed, the active menu item corresponding to the current URL is not set. After struggling to find a solution online, I manag ...

Refreshing the Date Display with AJAX Response

Within a view, there is a DisplayFor connected to a DateTime field in the Model. After an AJAX call returns a Date to update the field, I am able to convert the AJAX date into a MM/DD/YYYY format. However, using .val to set the DisplayFor does not reflect ...

Establishing the state of a toggle button after a modification in NextJS/React

One feature I'm currently working on involves a series of toggle buttons that switch between the values 'pending' and 'active'. Whenever a toggle button is clicked, a post request is sent to update the value in the database. Howeve ...

Efficiently managing desktop and mobile pages while implementing lazy loading in Angular

I am aiming to differentiate the desktop and mobile pages. The rationale is that the user experience flow for the desktop page involves "scrolling to section", while for the mobile page it entails "navigating to the next section." The issue at hand: Desk ...

Enable users to handle the version of a dependency in an npm package

As I develop a module that relies on THREE.js, I am exploring the most effective method to include THREE as a dependency and ensure accessibility for both the module and its users. My goal is to provide users with access to the THREE library within their p ...

Issue: Connection Problem in React, Express, Axios

I've encountered an issue while attempting to host a website on an AWS EC2 instance using React, Express, and Axios. The specific problem I'm facing is the inability to make axios calls to the Express back-end that is running on the same instanc ...

Learn how to switch between search and results views in Angular while also transferring data

Currently, I'm attempting to tackle a common task that I've yet to encounter an example of. Display 1 and Control 1 : In this view, there is a basic textbox with ng-model="searchTerm" and ngSubmit event. After the user enters their search term, ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

What is the functioning process of the angular method decorator?

The tutorial on creating custom decorators in Angular introduces a throttle decorator that utilizes the lodash throttle function. The implementation of this decorator can be seen below: import t from 'lodash.throttle'; export function throttle( ...

Incorporating Chip into a Material-UI DataGrid column

I'm having trouble displaying data of a specific column inside a chip. I attempted to use the Chip component in my code: StackBlitz Demo Web Link: Live Demo I tried to incorporate it using: import Chip from '@mui/material/Chip'; but c ...

Transforming a JSON object into a list in C#

After exploring similar posts without success, I am reaching out here for help. I have a Json data stored in a hidden field that I am trying to access in the code behind file of my markup page. My goal is to convert this Json into a List and bind it to a ...

Accordion jQuery failing to display tabs

I have a question about using 2 jQuery accordions with tabs inside them. Everything seems to be working, but when I try to expand the second accordion, the two tabs inside don't render properly. I'm not sure what the issue is. Any help on this wo ...

In Javascript, you can compare an array with a nested array and then store the values in a new array

Two arrays are at hand const arrayOne = [ {id: '110'}, {id: '202'}, {id: '259'} ]; const arrayTwo = [ {data: [{value: 'Alpha', id: '001'}]}, {data: [{value: 'Bravo', id: '202'}]}, ...

Formik is encountering errors and warnings while loading the Material UI autocomplete component

Hey there! I've been working on a code sample for an Autocomplete component using Material UI in next JS with formik. Unfortunately, I'm running into some errors and warnings upon loading the code. Despite trying various solutions found online, n ...

Ways to insert text into an SVG file

I am currently using vue-svg-map with a USA map. I am trying to display the state code (path.id) on my svg map. Can anyone provide guidance on how to achieve this? <radio-svg-map v-model="selectedLocation" :map="usa" :location-class="getLocation ...

Preserving CSS styling while loading an HTML page with InnerHTML

By using the following code snippet, I have successfully implemented a feature on my website that allows me to load an HTML page into a specific div container when clicking a link in the menu. However, I encountered an issue where the background color of ...

Using AJAX to dynamically load content from a Wordpress website

Currently, I have been experimenting with an AJAX tutorial in an attempt to dynamically load my WordPress post content onto the homepage of my website without triggering a full page reload. However, for some reason, when clicking on the links, instead of ...