DEV Community

Discussion on: Where to initiate data load in NgRx

Collapse
 
wheeleruniverse profile image
Justin Wheeler • Edited

What a great post! I often struggle with the best approach to load the data. For small apps I like the idea of loading the data in the App Component, but I don't like the idea of loading data that may never be used. For example, if a lazy loaded feature is never interacted with by the user after the data is eagerly loaded.

In my own project I've created a Facade to abstract the NgRx layer from the rest of the Angular code. In there I am dispatching the Load action if the selector does not have the data loaded. This worked best for me, yet I still feel like it violates the NgRx best practices.

At least with this approach I don't need to worry about dispatching a load from my components. Just retrieve() the data and it will pull it from the service or the store.

  retrieve(): Observable<CertificationState> {
    return this.store.select(certificationStateSelector).pipe(
      tap((state) => {
        if (state?.data == null) {
          this.store.dispatch(new CertificationRetrieveAction());
        }
      })
    );
  }
Enter fullscreen mode Exit fullscreen mode

certification.facade.ts