Mathias F
Mathias F

Reputation: 15891

Combine selectors only when both emited values

I have 2 selectors selectAllJournals, selectAllAccounts that emit values at different times.

The combined selector needs a value from selectAllAccounts as soon as there is a value emitted from selectAllJournals. Right now I check in the mapping function mapJournalListViewModel if the selectAllAccounts emitted values. But that feels awkward. One problem I see is that mapJournalListViewModel will be callled twice: once for an emitted value from selectAllJournals and selectAllAccounts. Is there a better way, so that mapJournalListViewModel only gets called when both selectors emitted values?

export const selectJournalListViewModel = createSelector(
  selectAllJournals,
  selectAllAccounts,
  (journals, accounts) =>
    journals.map((j) => mapJournalListViewModel(j, accounts))
);



function mapJournalListViewModel(
  journal: Journal,
  accounts: Account[]
): JournalListViewModel {
  return {
    id: journal.id,
    date: journal.date,
    debitAccountName: accounts?.find(
      (a) => a.id === journal.transactions[0].account.id
    )?.name!,  // <--- accounts checked for null because the selector might emit values only later
   
  };

Upvotes: 0

Views: 44

Answers (1)

wlf
wlf

Reputation: 3393

Just use conditional logic:

export const selectJournalListViewModel = createSelector(
  selectAllJournals,
  selectAllAccounts,
  (journals, accounts) =>
    (journals && accounts) ? journals.map((j) => mapJournalListViewModel(j, accounts)) : []
);

Upvotes: 0

Related Questions