Your NGRX Effects are Probably Wrong

If you are like me, you probably have some NGRX Effect that looks something like this:

In this simple effect, we are saving a pizza via a HTTP service. This is wrong though! Heres the right way:

Do you see the difference? Its subtle but can be a huge difference in production; instead of switchMap, I used concatMap.

Whats the difference you say? Well the switchMap can cause race conditions. With a switchMap it will cancel and replace the prior observable with a new value that came through. So if this were to execute twice before the first one completed, you would loose the first one! Thats a pretty big deal for things like save/update/delete.

Now there are cases where you want to use a switchMap, lets say you have a typeahead where as the user types, you want to fetch the new results and you really don’t care about the previous result.

Now using a concatMap can slow down things because it executes them sequentially. If you don’t care about order, I’d suggest a mergeMap. It will preserve all the requests but execute them right away rather than waiting for the previous to succeed.

To help illustrate the difference, checkout this demo: https://stackblitz.com/edit/switchmap?file=app%2Fapp.component.ts

The difference is subtle but important because it can cause unexpected behavior that will take forever to track down. Knowledge is power!

Special thanks to Bonnie Brennan for pointing this out and crafting this article!

I’m #ngPanda

I hope you enjoyed the post, if you liked it follow me on Twitter and Github for more JavaScript tips/opinions/projects/articles/etc!