Reselect for Components

Slides: https://goo.gl/photos/3DWETLDtTM8j13mF6

To deal with derived data, Redux recommends to use Reselect. With ngrx/store you can use RxJS CombineLatest operator.

Let’s imagine that the following object is your application state:

{
  "users": {
    "293580923": { "username": "shprink"},
    "423948745": { "username": "byjc"},
    "435435799": { "username": "myagoo"},
    "027859645": { "username": "whoknows"},
    ...
  },
  "trendingUsers": [293580923, 435435799, ...],
  "topUsers": [423948745, 027859645]
}

To get the trendingUsers or topUsers list of users you need to merge them with the actual users objects from the users key.

CombineLatest emits an item whenever any of the source Observables emits a new item.

rx_combinelatest_operator

To get the list of trendingUsers with just CombineLatest operator, here is what you need to do:

you can easily displayed the list of trendingUsers with the async pipe:

import { Store } from '@ngrx/store';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/combineLatest';
@Component({
    template: `
      <div *ngFor="let user of (usersStream$ | async)">
        {{user.username}}
      </div>
    `
})
export class TrendingUsersComponent {
  usersStream$: Observable<Array<IUserState>>;
  constructor(
    public store: Store<AppState>
  ) {
    this.usersStream$ = Observable.combineLatest(
      store.select('users'),
      store.select('trendingUsers'),
      (users: IUsersState, trendingUsers: Array<number>)
        => trendingUsers.map(id => users[id]))
  }
}

You don’t need reselect

The select() method will give you an observable that calls distinctUntilChanged() internally, meaning they will only fire when the state actually changes. ( it means when there is a new reference ).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s