Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to get NGRX data from multiple slices of the store

Tags:

angular

rxjs

ngrx

Is there a best practice for getting data from multiple slices of an NGRX store? I'm using NGRX entity and I have a slice for companies, users, vendors, and orders and in a particular component, I need to access all 4. I've tried a few different methods but they all seem cumbersome.

Should I use 4 separate selectors from multiple entities or is it better to make a selector at the root level and include everything needed for the details page?

Currently, I'm using a combineLatest operator

this.subscription.add(this.store.select(fromUser.getUsers).pipe(
    combineLatest([
        this.store.select(fromCompanies.selectAll),
        this.store.select(fromVendors.selectAll),
        this.store.select(fromOrders.getOrders),
    ]))
like image 248
mattc19 Avatar asked Sep 19 '25 05:09

mattc19


1 Answers

I find the best way to combine selectors is by using selectors, this will also be the most performant way because NgRx does some optimization here.

A createSelector can be composed from multiple selectors, in your case this would be:

export const foo = createSelector(
  fromUser.getUsers,
  fromCompanies.selectAll,
  fromVendors.selectAll,
  fromOrders.getOrders,
  (users, companies, vendors, orders) => {
     // logic here
  }
)

For more info see Sharing data between modules is peanuts

like image 93
timdeschryver Avatar answered Sep 20 '25 19:09

timdeschryver