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();
}