API call inside ngrx subscriber

398 views Asked by At

Are there any drawbacks / considerations to be made with making API calls inside subscribers? Or is there a preferred approach to this problem? An example:

this.store.select('person').subscribe(person => {
    this.http.get(`/tasks/${person.id}`)
        .map(res => res.json())
        .subscribe(tasks => {
            // Dispatch tasks.update
        });
});

Any thoughts would be appreciated.

Tom

1

There are 1 answers

5
maxime1992 On

I don't think that calling an HTTP method like that is a good idea.

For example :
- Your person is updated
- The HTTP request is fired
- You dispatch an action to save the changes into the store
- As the store is updated, you'll have another HTTP request launched
- Etc, etc

You'll end up with a loop and DDOS on your backend.

Instead of that, you should rather dispatch an action FETCH_PERSON, catch it with an Effect and once you get the response in the effect, dispatch another action according to the response (FETCH_PERSON_SUCCESS or FETCH_PERSON_ERROR for example).