How to make sure all data is written into Firestore in a sequential order?

Viewed 105

I'm trying to create a user profile that states that that profile is from one of the business owners in my app. It is supposed to create the profile and then merge info such as the 'roles' array with 'businessOwner' in it and also add the 'businessId'.

Sometimes, the code will work seamlessly. At other times, only the roles and the businessId will be passed to the created user (and all of the other information won't!).

  async function writeToFirebase(values) {
    authService.createUserWithEmailAndPassword(values.user.email, values.user.senha).then(
      async function (user) {
        userService.createUserProfileDocument(values.user)
        const uid = user.user.uid
        const userRef = await userService.doc(uid)
        console.log('userRef', userRef)
        try {
          values.user.uid = uid
          const { id } = await businessPendingApprovalService.collection().add(values)
          await userRef.set({ roles: ['businessOwner'], businessId: id }, { merge: true }) 
        } catch (error) {
          console.error('error merging info')
        }
      },
      function (error) {
        var errorCode = error.code
        var errorMessage = error.message
        console.log(errorCode, errorMessage)
      },
    )
  }

This is createUserWithEmailAndPassword:

async createUserProfileDocument(user, additionalData) {
    if (!user) return
    const userRef = this.firestore.doc(`users/${user.uid}`)
    const snapshot = await userRef.get()
    if (!snapshot.exists) {
      const { displayName, email, photoURL, providerData } = user
      try {
        await userRef.set({
          displayName,
          email,
          photoURL, 
          ...additionalData,
          providerData: providerData[0].providerId,
        })
      } catch (error) {
        console.error('error creating user: ', error)
      }
    }
    return this.getUserDocument(user.uid)
  }
2 Answers

I think that the issue is on this line const snapshot = await userRef.get().

As stated in documentation you should fetch the snapshot using then() function in order to return the promise first.

I think you need to await on the below as well:-

await userService.createUserProfileDocument(values.user)

Since you are setting the user info here(await userRef.set), if you will not wait for the promise, then sometimes, your next block of code(await userRef.set({ roles: ['businessOwner'],) executes and after then your promise might get resolved. Because of this, you might not get the other information sometimes.

You also need to handle the error case of createUserProfileDocument.

Related