Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ngrx: combine two selectors

Tags:

I've built this IStore:

export interface IStore {   user: IUser;   sources: ISourceRedux; } 

where IUser is:

export interface IUser {     id: string;     cname: string;     sname: string;     ... } 

and ISourceRedux is:

export interface ISourceRedux {     entities: { [key: string]: ISource };     ids: Array<string>;     selectedIds: Array<string>;     editingSource: ISource;     defaultId: string; } 

So, I've created these selectors:

export const getSourcesState = (state: IStore) => state.sources; export const getSelectedIds = (sourceRdx: ISourceRedux) => sourceRdx.selectedIds; export const getSelectedSourceIds = createSelector(getSourcesState, fromSources.getSelectedIds); 

So, up to now, in order to check if a user is logged I did that:

this.store$   .select(fromRoot.getUserState)   .filter(user => user.id != null && user.logged)   .do(user => this.store$.dispatch(...))   ... 

Now I'm strugling for getting user information and selectedSourceIds at the same time in order to check if:

  1. a user is logged (this.store$.select(fromRoot.getUserState)
  2. then get all selectedSourceIds (this.store.select(fromRoot.getSelectedSourceIds))
  3. dispatch an action

How could I get this?

like image 740
Jordi Avatar asked Apr 06 '17 13:04

Jordi


1 Answers

Would it make sense to add that code to a selector:

// Selector functions const getProductFeatureState = createFeatureSelector<ProductState>('products'); const getUserFeatureState = createFeatureSelector<UserState>('users');  export const getCurrentProduct = createSelector(   getProductFeatureState,   getUserFeatureState,   getCurrentProductId,   (state, user, currentProductId) => {     if (currentProductId === 0) {       return {         id: 0,         productName: '',         productCode: 'New',         description: 'New product from user ' + user.currentUser,         starRating: 0       };     } else {       return currentProductId ? state.products.find(p => p.id === currentProductId) : null;     }   } ); 

This code is in the product.reducer file. Here I define the feature selector both for the products and for the users.

I then build a getCurrentProduct selector using both the product and user feature.

like image 190
DeborahK Avatar answered Oct 01 '22 08:10

DeborahK