Dispatch action inside selector NGRX

In my selector I'm checking if the data in the store is loaded and corresponds the router parameters. The router is "source of truth", so if data is not loaded I'd like to send an action to fetch it. Is it ok to do such things in selector?

  (currentGameState, router): Game => {
     if (currentGameState.game.id === router.state.params.gameId && 
         currentGameState.isLoaded) {
         return currentGameState.game;
     }
  }

Upvotes: 2

Views: 3728

Answers (1)

Tony
Tony

Reputation: 20082

Side effect are handle by effect class (dispatch action, call api etc).

Selector only use to get data out from the store using async. Which mean not doing any side effect like dispatch action in here.

Update normally you need to do initialize data loading in ngOnInit

export class PostComponent implements OnInit {
  public posts$: Observable<IPost[]>;
  constructor(private store: Store<IPostManagementState>) {}
  ngOnInit(): void {
    this.store.dispatch(new GetAllPosts());
    this.posts$ = this.store.pipe(select(selectPostList));
  }
}

Then using async pipe in view

<div *ngFor="let post of posts$ | async">{{ post.body }}</div>

You can view the code here

Upvotes: 6

Related Questions