Access account and refresh user document when onAuthStateChange occurs

When signing in to Firebase and updating the user doc using merge: true, an issue arises when the onAuthStateChanged listener is also active. This listener detects new logins and then reads the user doc, causing potential conflicts.

Upon further inspection of the functions provided:

export const signInAndUpdateUserObject =
  (provider: AuthProvider) => async (): Promise<void> => {
    try {
      const { user } = (await signInWithPopup(provider)()) ?? {};
      if (!user) {
        return;
      }

      await setDoc(doc(getFirestore(), 'users', user.uid), {}, { merge: true }); // Merging an empty object
    } catch (err) {
      console.error(err);
    }
  };

export const initAuth = (): void => {
  auth.onAuthStateChanged(async (user) => {
    if (user) {
      const docRef = doc(getFirestore(), 'users', user.uid);
      const exists = await getDoc(docRef);
      console.log(exists); // THIS WILL SHOW AN EMPTY OBJECT
    } else {
      return;
    }
  });
};

(The initAuth function is triggered when the app starts). In this example, the user doc is updated with an empty object for simplicity. Although merge prevents changes to the entire document, a peculiar behavior occurs when reading the user doc in onAuthStateChanged. It seems to only read the merged object, resulting in unexpected outputs. If merge: false were used instead, the user doc would be correctly retrieved, but this solution is not desirable.

To address this dilemma, introducing a slight delay via setTimeOut within the onAuthStateChanged function resolves the issue:

export const initAuth = (): void => {
  auth.onAuthStateChanged(async (user) => {
    if (user) {
      setTimeout(async () => {
        const docRef = doc(getFirestore(), 'users', user.uid);
        const exists = await getDoc(docRef);
        console.log(exists); // Will show the complete user doc object
      }, 3000);
    } else {
      return;
    }
  });
};

Answer №1

Seems like you're pulling data from the local cache with incomplete information. In this scenario, the metadata.fromCache property in the snapshot should be set to true, along with potentially having metadata.hasPendingWrites as well. Check out the official documentation on metadata for further details.

Here are a couple of options:

  • Indicate that you prefer fetching the data from the server using specific source options
  • Connect a realtime listener and wait until an update is received with both fromCache and hasPendingWrites set to false.

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

Employing buffers and streams for data transmission

I am in need of a node.js program that can effectively handle a large JSON dataset with thousands of records. Specifically, I require a script that can extract only the "name" key from each record and transfer it to another file using streams. If there ar ...

Tips on how to store the values of dynamically generated textboxes into a variable

Trying to insert dynamic values from multiple rows of textboxes into a variable, then send it through ajax json to the server side. This is the code for generating multiple dynamic values. $('#btnASize').click(function() { var sizerangeMin = " ...

Execute a function upon mounting of an API endpoint

I have been working with an Express router in my application. I am trying to execute a function when a specific route is mounted. The setup involves two files, index.route.js and currentUser.route.js. index.route.js import currentUserRoutes from './ ...

Altering data in Firebase's storage metadata

Within my iOS application, users have the ability to upload profile images, which are then stored in Firebase storage. To keep track of the URLs associated with each user, I store them in the database using the code snippet below: let storageRef = FIR ...

Why isn't the AngularJS injected view resizing to fit the container?

As a novice delving into a project in the MEAN stack, I'm encountering inconsistent HTML previews. When I view it independently versus running it from the project, the display varies. Here's the intended appearance (in standalone preview): imgu ...

Avoiding memory leaks when using three.js with a large number of shapes

My code is devouring memory at an alarming rate and ultimately crashing. After some investigation, I've determined that the issue seems to be related to the torus generation/removal portion of the code. Despite efforts to manage the scene array and t ...

Tips for monitoring a field within an angularJS factory

Within my web application, I am utilizing a factory. This factory contains an object named mapLayers. Within my controller, I am assigning this factory.mapLayers object to a variable on the scope called $scope.mapLayers and using ngRepeat to iterate over i ...

Adding an item to the EmberJS Data Store

Is there a way to add a record to the Ember Data Store without relying on the adapter? Whenever I use this.store.push({type: type, data: data}), the store always sets the hasDirtyAttributes flag to true. To work around this issue, I have been using this. ...

Displaying the overall count for a bar chart within the tooltip title of a c3js visualization

I have a bar chart that looks similar to the one presented in this example. There are two specific features I am interested in adding to this bar chart: Instead of numeric values, I would like the tooltip title to show the sum of the counts represente ...

Framework7 disables the jQuery.appear plugin

I am utilizing Framework7 and aiming to incorporate jQuery.appear for executing a script once an element becomes visible to the user. The implementation is successful when using this code in a basic HTML setup: <!DOCTYPE html> <html> < ...

The UI router fails to render the template

I've recently started working with ui-router, but I'm facing an issue where nothing shows up in the ui-view. To simplify things, I even tried adding it to Plunker but still couldn't get it to work. Here's a link to my project: https://p ...

How can we efficiently validate specific fields within arrays and objects in express-validator by utilizing the body() method?

I have organized my field names in an array as follows: const baseFields = [ 'employeeNumber', 'firstName', 'lastName', 'trEmail', 'position' ]; These are the only input fields I need to focus on for valid ...

The TextBox will alter its color following an incorrect submission

I am struggling to create a bootstrap form that will change the color of the borders to red after incorrect submission. The issue I am facing is that the textbox always remains in red. Does anyone have any suggestions for setting the textbox borders to red ...

Getting a Cookie in React from an Express JS API (MERN Stack)

My API in Express JS stores a token in a cookie on the client-side (React). The cookie is generated only when a user logs into the site. When testing the login API with Postman, the cookie is generated as expected: https://i.sstatic.net/rL6Aa.png However ...

Enabling hover effects to scroll divs only when interacted with

I am aiming to achieve two separate scrolling divs and I'm uncertain about the exact approach. Experimenting with various overflow properties has only resulted in one scrolling independently. .profile { width: 100%; display: flex; ...

guide to setting up router access using token

I've received a token from the backend axios.post(process.env.VUE_APP_LOGIN, payload) .then(response => { const {access_token, token_type, user} = response.data; this.token = access_token this.$store.commit(&a ...

The event handler is not being triggered when selecting the tag

Currently working on a project where I am utilizing vanilla HTML/CSS/JS. My goal is to hide all items on a page initially, set a default option in a select tag, display only the element with the selected ID, and allow the user to choose different time peri ...

Is there a way to use JQuery to determine which button in a table was clicked and retrieve all the data from that specific row?

Below is the HTML code: <table class="table table-stripped table-bordered table-hover centerAll" cellpadding="10"> <thead> <th>Nombre</th> <th>Descripci ...

Executing a mousedown event in Ajax while simultaneously running another JavaScript function using JQuery

One issue I am facing involves a JavaScript method. There is a date slider for months that triggers an AJAX call when the month is changed (mouseup event). Within this AJAX call, there is another JavaScript code ($.blockUI) which seems to interfere with th ...

This browser does not recognize the tag <>. To render a React component, ensure its name starts with an uppercase letter

MyIcons.tsx export const ICONCAR = () => ( <span className="svg-icon svg-icon-primary svg-icon-2x"><svg xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="24px" height=&qu ...