Search code examples
angularrxjsangularfire2

How to handle an observable that may return empty when using switchMap RxJS


how should the following scenario be handled with RxJS?

I have an observable that queries my Firestore database for a submission by an ID extracted from the url parameters:

this.submission$ = this.db.collection$('submissions', ref => ref.where('submissionArtistUID', '==', this.artistParam));

For elements subscribed to this observable the submission$ returns an array of submission objects. Thus I can use switchMap to query my users table once the submission$ has resolved:

this.user$ = this.submission$.pipe(
  switchMap(
    (submissions) => {
      return this.db.collection$('users', ref => ref.where('userUID', '==', submissions[0].submissionUserUID ))
    }
  )
)

However, the submissions query is not guaranteed to return anything. So when I used the switchMap on a submission that returns empty, I cannot access the following property: submissions[0].submissionUserUID, and I'm shown this error in console:

Cannot read property 'submissionUserUID' of undefined

Which makes sense because the submission$ resolves to an empty object before trying to be used in the return statement of the switchMap.

So how do I account for scenario like this using RxJS? Is switchMap the right thing to use? Thanks!


Solution

  • You can use filter operator before switchmap. Your code might look like this.

    this.user$ = this.submission$.pipe(
    filter(submissions => Object.keys(submissions).length > 0),
      switchMap(
        (submissions) => {
          return this.db.collection$('users', ref => ref.where('userUID', '==', submissions[0].submissionUserUID ))
        }
      )
    )