1

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!

1 Answer 1

3

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 ))
    }
  )
)
Sign up to request clarification or add additional context in comments.

2 Comments

very concise, filter did the trick! Thanks for teaching me an application of that operator :)
Awesome. Glad to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.