Search code examples
ngrxngrx-effects

How to recover data from a state instantly?


I start using NgRx and am a little lost to access the data contained in the State. I searched several hours before asking my question because I did not really find an answer.

When using NgRx to display the data on a list, it's fabulous. I wanted to go more using NgRx to group the settings of my application with my SettingsState.

I would like to put particular in my SettingsState: - the base URL for API requests, - the number of lines to display in a list: important during API requests to limit the data to be retrieved. - ...

When I'm in an Effect, how can I directly retrieve my important parameters to launch my API requests?

I understood that to recover the data, it is necessary to use the "selectors" to obtain an "Observable" which will allow me to be informed as soon as a change will arrive.

However, here I want the values ​​now without waiting to launch my API requests. How can I do ?

thank you in advance


Solution

  • As you correctly pointed out, you should use selectors to access Data from your store. You can use selectors in components, but also in effects.

    Look at this example effect:

    @Injectable()
    export class ElementEffects {
    constructor (private store: Store<any>, private apiService: ApiService) {}
    
          @Effect()
          public yourEffect: Observable<Action> = this.actions$.pipe(
            ofType<yourActionClass>(ActionsEnum.YOUR_ACTION),
            withLatestFrom(this.store.pipe(select(selectSomethingFromTheStore))),
            concatMap(([action, selectedDateFromTheStore]) => this.apiService.doBackendCall(selectedDateFromTheStore, action.payload).pipe(
              map(([resultFromTheBackendCall, selectedDateFromTheStore]) => {
                // Do Stuff
              },
              catchError((error) => of(new FailureAction(error)))
              )
            ),
          );
    }
    

    The "withLatestFrom" allows you to add another observable to your chain. You will have the result instantly and you can use it.

    https://www.learnrxjs.io/operators/combination/withlatestfrom.html