Timing issues during the sign-up process and triggering onAuthStateChanged() in a Vue application are leading to complications with user permissions

In my Vue application, I am looking to register users, create a user document, and then fill the state with relevant information by fetching data from a document in Firebase.

I want to follow this sequence because if the tasks do not execute synchronously, the app will attempt to retrieve the state information from Firebase before the document is actually created.

It appears that the problem stems from using createUserWithEmailAndPassword() first, followed by creating a user document. When the authentication function triggers, onAuthStateChanged() is called, which attempts to fetch the user document (even before it has been created), resulting in a permissions error.

Within userAuth.vue - THE ISSUE ARISES AS SIGN-UP TRIGGERS ONAUTHSTATECHANGED, WHICH TRIES TO FETCH THE USER DOCUMENT BEFORE THE SETDOC FUNCTION BELOW IS EXECUTED. Could this be due to the asynchronous nature of the promise in the handleAuth() action?

 await store.signUp(email.value, password.value);
 const docRef = doc(db, "users", store.userId);
 await setDoc(uDocRef, {
          //user data
        })

The Pinia store general.js includes the sign-up flow and handleauth flow

async signUp(email, password) {
  try {
    const res = await createUserWithEmailAndPassword(auth, 
    email, password);

    this.user = res.user;
    this.userId = res.user.uid;

  } catch (err) {
    console.log(err);
    await this.signOut();
    throw new Error("could not complete signup");
  }

},
async handleAuth() {

  const auth = getAuth();
  return new Promise((resolve) => {
    auth.onAuthStateChanged(async (user) => {

      if (user) {
        await this.setAuthIsReady(true);
        let info = await this.getUserInfo(user.uid);
        await this.setUser({
          //user document data
        });

        }

        resolve();
      } else if (!user) {
        await this.clearUserData();
        await this.setAuthIsReady(false);
        resolve();
      }
      
    });
  });
},

In the router index.js

Router.beforeEach(async (to, from, next) => {
 const authStore = useGenStore();

if (authStore.isAuthenticated != true) {
  await authStore.handleAuth();
}

Answer №1

Unfortunately, I am away from my computer at the moment, but based on your query, here are a few suggestions you can experiment with:

  1. It seems like you are trying to use await for the store function to sign up, but this is not a promise so the await statement may not work as expected. Consider moving the setDoc function inside the signup function immediately after "const res = createUser...". It seems like these actions need to be performed together.
  2. Have you verified if "store.userId" is accurate? It might be more appropriate to use something like "store.state.user.uid" instead.
  3. Similarly, double-check if "uDocRef" is correct. The variable mentioned just before is "docRef", so there might be some confusion there.

I hope one of these suggestions proves helpful! Best of luck resolving your issue.

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

Trying to follow a guide, but struggling to identify the error in my JavaScript syntax

I'm attempting to follow an older tutorial to change all references of the word "cão" on a page to "gato". These instances are contained within spans, and I'm using the getElementsByTagName method in my script. However, when trying to cycle thro ...

Rendering components before ComponentDidMount runs and Axios handles state updates

When I try to pass the gifs state to my GifList component in the render method, I encounter an issue. It seems that when trying to access the array within the component through props, it is returning as undefined. After investigating further, I noticed t ...

In order to trigger the mousedown event in Three.js, I have found that I need to click and gently move my cursor

There seems to be an issue with the code below, as the "intersects" variable does not populate with items in the onDocumentMouseDown event handler when I simply click an object. It only detects the object clicked when I click and slightly drag the mouse be ...

Ways to guarantee a distinct identifier for every object that derives from a prototype in JavaScript

My JavaScript constructor looks like this: var BaseThing = function() { this.id = generateGuid(); } When a new BaseThing is created, the ID is unique each time. var thingOne = new BaseThing(); var thingTwo = new BaseThing(); console.log(thingOne.id == ...

Trouble with sending semicolons in Node.js MSSQL/MSNodesqlv8 database queries

Trying to create a simple API for interacting with a MSSQL v12 database using Nodejs. Successfully connected to the database with the mssql/msnodesqlv8 package, but encountering issues with parameterized queries. code: 'EREQUEST', number: 102 ...

Validate input strings in Node.js using Joi to detect and return an error if there are leading or trailing spaces

Looking to set up JOI validation in Node.js that flags errors if a string begins or ends with an empty space. For example: name = "test123" //valid name = "test(space)" or "(space)test" // invalid ...

Strategies for including JavaScript variables in AJAX data

I have a basic webpage displaying employee names that can be dragged around using Jquery UI draggable. I am able to capture the "top" and "left" position of the dragged item and store it in a JavaScript variable. My next goal is to pass these two variable ...

Designing a custom HTML calendar

I am currently working on a school project where I am creating a calendar using HTML. So far, I have set up the basic structure of the page. What I want to achieve is a functional calendar where users can create appointments that will be displayed accordi ...

Transferring Client Files to Azure Blob Storage using MVC Framework

After setting up a WebApp(MVC4) with a file upload feature, I made a major error by allowing clients to upload files directly to my server (Virtual Machine Azure). To make this work, I adjusted the following settings in my WebConfig: maxRequestLength="2 ...

Successfully resolved: Inability to dynamically adjust button color according to its state

Currently I am working on a feature where a button changes color when it is disabled, but also has a custom color when enabled. Here is the code snippet I am using: Despite setting blue text for the button, it remains blue even after becoming disabled. Ho ...

Tips for displaying a loading spinner each time the material table is loading

Hey there, I'm currently working on an Angular project where I need to display a table using Material Table. To indicate that the table is loading, I've defined a variable called isLoading. Here's how it works: In my TypeScript file: @Com ...

The reactivity of a variable is not being properly updated by Vuetify

I've been trying out external pagination with Vuetify following this example: https://vuetifyjs.com/en/components/data-tables/pagination/#external-pagination. The only difference is that my code fetches data asynchronously, but for some reason, it&apo ...

Is utilizing the service through the bootstrap application providers equivalent to specifying providedIn: root when declaring the service?

Let's consider a scenario where we have a service named SomeService that is defined within a library without the providedIn: root injectable metadata configuration. @Injectable() export class SomeService { ...} Now, in our application, we include Som ...

No content sent in the request body while implementing fetch

Attempting to send graphql calls from a React component to a PHP server using the fetch method for the first time. The setup involves React JS on the client-side and Symfony 4 on the server-side. Despite indications that data is being sent in the browser ...

Adding an <a> tag to Flickity: Step by step guide

Is there a way to incorporate tags into a Flickity image slider without affecting its functionality? Here's the code snippet I have for the slider: <div class="carousel" data-flickity='{ "imagesLoaded": true, "percentPosition": false, "auto ...

Oops! Looks like node.js is throwing an error with the message "connect ECONNREFUSED"

After creating a node.js application that interacts with a locally installed MySQL database, I encountered an issue where running the app through CMD (npm start) returned the desired results, but testing it through Postman resulted in an error: connect E ...

Include authentication headers in the native video element

I have integrated videojs-player for Vue to showcase videos fetched from my backend system. The backend of my application is powered by Django REST Framework (DRF) while the frontend utilizes a Vue SPA. Authentication is handled through token retrieval du ...

Ignore missing values when performing an upsert operation

I'm currently utilizing pg-promise to manage my Postgres queries, but I've hit a roadblock with the following query conundrum: My goal is to develop a single method that can batch upsert multiple rows simultaneously. Here's the code snippet ...

Tips for utilizing formidable with NextJS 13 API for image uploading and resolving request errors

I've been working on integrating image uploading functionality into my application. I'm currently using NextJS version 13.4.4 along with formidable@v3. However, whenever I attempt to upload an image, I encounter the following error: error TypeE ...

What is the best way to showcase a PDF file on a webpage with multiple thumbnails using JavaScript or jQuery?

I recently undertook a project at work that involved displaying multiple PDF thumbnails/images on a webpage. These files were dynamically loaded from a directory on my system. Each thumbnail corresponded to a PDF file stored in a different directory. My g ...