javascriptreactjsreselect

Reselect - how to pass a result of one selector to another as an argument before combiner function?


I have a selector that looks like this:

export const shipmentsRejectedSelector: (
  state: AppStateType,
  departmentIds: List<number>,
  currentDate: DateTime,
  toDate: DateTime
) => List<Shipment> = createImmutableEqualSelector(
  shipmentsByDepartmentIdsAndDate,
  packageEvents,
  (shipments, events) =>
    shipments
      .valueSeq()
      .filter(s => s.get('state') == EventType.REJECTED))
      ?.toList() || List()
)

Since packageEvents returns all events no matter what shipments it is part of, I would like to return only events that are part of the shipments returned by the shipmentsByDepartmentIdsAndDate selector. How can I pass shipmentIds to a new selector that would fetch only events that have the shipmentIds that I am passing? Something like this for example:

export const shipmentsRejectedSelector: (
      state: AppStateType,
      departmentIds: List<number>,
      currentDate: DateTime,
      toDate: DateTime
    ) => List<Shipment> = createImmutableEqualSelector(
      shipmentsByDepartmentIdsAndDate,
      shipments => packageEvents(shipments),
      (shipments, events) =>
        shipments
          .valueSeq()
          .filter(s => s.get('state') == EventType.REJECTED))
          ?.toList() || List()
    )

Solution

  • In your code you've not shown how you are using the event object in resultFunc(combiner). So I am guessing you want to add events to the shipments before filtering them.

    One way could be to use the packageEvents in combiner:

    const shipmentsByDepartmentIdsAndDate = ...;
    const shipmentWithPackageEvents = createSelector(shipments, (shipments)=>{//return shipments along with the corresponding events});
    
    const shipmentsRejectedSelector = createSelector(
          shipmentsByDepartmentIdsAndDate,
          (shipments) =>
            shipmentWithPackageEvents(shipments).valueSeq()
              .filter(s => s.get('state') == EventType.REJECTED))
              ?.toList() || List()
        )
    

    Or we can directly use shipmentWithPackageEvents:

    const shipmentsByDepartmentIdsAndDate = ...;
    const shipmentWithPackageEvents = createSelector(shipments, (shipments)=>{//return shipments along with the corresponding events});
    
    const shipmentsRejectedSelector = createSelector(
          shipmentWithPackageEvents,
          (shipments) =>
            shipments.valueSeq()
              .filter(s => s.get('state') == EventType.REJECTED))
              ?.toList() || List()
        )