0

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
   
  };
Mathias F
  • 15,906
  • 22
  • 89
  • 159

1 Answers1

0

Just use conditional logic:

export const selectJournalListViewModel = createSelector(
  selectAllJournals,
  selectAllAccounts,
  (journals, accounts) =>
    (journals && accounts) ? journals.map((j) => mapJournalListViewModel(j, accounts)) : []
);
wlf
  • 3,086
  • 1
  • 19
  • 29