'combine states of 2 redux stores

I have 2 stores, one about properties and one about owners. Each property is owned by one or more owners, and I have to group the properties by owner. So like a map structure Map<Owner, Property[]>.

How to I retrieve both objects you ask? Redux selectors!

For properties I have a facade which has a selector

properties$ = this.store$.select(PropertySummarySelectors.selectProperties);

This is what is used now, to show a list of all properties on a page, now we have to add a tab, which will group the properties by owner. Why doesn't property have data about the owner, the owner is human and we can't store personal information on our side, privacy stuff.

In another store for owners, we also have a facade, which has a selector that I need

 ownersOfProperty$ = (propertyId) => this.store$.select(OwnerSelectors.selectOwnerForProperty, propertyId);

This will return a list of owners for the given property using the following selector:

  export const selectOwnerForProperty = createSelector(
    selectOwnerForProperty,
    (ownersPerProperty, propertyId) => ownersPerProperty[propertyId] || []
  );

So when calling the OwnerFacade, I get an Observable.

My idea was, when calling the property$ selector, for every object in that list, call the other facade to get the owners.

this.property$ = this.propertySummaryFacade.properties$.pipe(
        map(properties => properties.map(
            async property => {
              property.owners = await this.ownerFacade.ownerOfProperty$(property.id);
              return property;
            })
        )
    );

It doesn't resolve it, it looks ugly. How to I combine these 2 states for 2 stores correctly, without extending my Property object on the backend side, which is again not easy due to privacy regulation.



Solution 1:[1]

Create a selector that combines both entities.

const selectCombine = createSelector(
  selectEntities1,
  selectEntitities2,
  (ent1, ent2) => /* combine both into a single object */
)

Use that selector as a "base" selector

const selectOne = (id) => createSelector(selectCombine, combine => combine[id])

Use the selectOne selector in components.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 timdeschryver