Firestore onAuthStateChanged and users in a subcollection

Viewed 173

I'm building an app where users can authenticate, in Firestore I save extra data from that user (username, age).

Now in my app, users are coupled to events, I chose to have an events collection, which has a users subcollection.

I'm using the firebase onAuthStateChanged listener to see when my user has logged in. However the issue I'm not facing is, to get the firestore data for my user, I need to know which event this user belongs to, which is of course, data I do not have access to at the time the user signs in, for example:

const onAuthStateChangedPromise = new Promise((resolve, reject) => {
    auth.onAuthStateChanged(async firebaseUser => {
        if (firebaseUser !== null) {
            const user = await getDoc(doc(db, 'events/${eventId}/users', id))
            useAuth().user = user
            return resolve(user)
        }
        return resolve(null)
    }, err => {
        reject(err)
    })
})

In the example above, to get my user's data, I need to know the eventId, which I can not possible determine from the authenticated user.

I'm wondering how to achieve this?

  • I could save the eventId in localStorage as soon as the user registers, but that can cause issue's, since the complete app then relies on something being set on localStorage
1 Answers

The typical way to solve this would be to add the UID of the user in a field inside the events/${eventId}/users documents and then use a collection group query across all users collections. This will give you a list of all event/users docs for that user.

To find the event for such an event/user doc, you first take the DocumentReference for the DocumentSnapshot and then go up the parent chain twice to get to the parent event document.

Related