1

I am using rxfire to combine data from firestore in componentdidmount:

store$.pipe(
      withLatestFrom(items$),  
      map(([store, items]) => ({ items, ...store })),    
    ).pipe(   
      withLatestFrom(categories$),       
      map(([store, categories]) => ({ categories, ...store })),
    ).subscribe(store => {      
      this.setState({ store: store, isLoading: false });
    })   

The problem with this code is not firing and the screen stuck with the loading component. If I load the screen a second time it works. Am I doing something wrong? How can I fix it

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Aggounix
  • 251
  • 5
  • 15

1 Answers1

0

If it's not working until you reload, there could be a timing issue based on when items$ and categories$ emit their own values.

A safer approach to combining these observables would be with the combineLatest() feature from RxJS. It accepts an array of observables, and doesn't emit until it receives a value from every observable.

combineLatest([store$, items$, categories$]).pipe(
  map(([store, items, categories])=>({...store, ...items, ...categories})),
  tap(store=>this.setState({ store, isLoading: false })
).subscribe();

Keep in mind with combineLatest() that if any observable inside the array doesn't emit a value, then combineLatest() will never emit a value.

Joshua McCarthy
  • 1,739
  • 1
  • 9
  • 6
  • Thanks, it worked. I just changed this way: ``` map(([store, products, categories])=>({products, categories, ...store})), ``` Else what do you mean if collection does'nt emit?: meaning if categories or products are empty we will not have value at all? – Aggounix Jul 24 '21 at 09:09
  • If categories or products are empty, then it will emit an empty array. I was talking about whether or not the observable emits zero values. – Joshua McCarthy Jul 24 '21 at 09:41
  • Also, if this did help you, please mark this answer as resolving your question. – Joshua McCarthy Jul 24 '21 at 14:44