switchMap after filter drove me insane #3607
mikerentmeister
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hey all,
;tldr:
If you're going to do a switchMap on a store.select after using a filter operator, make sure to use the take(1) operator, or the first() operator!!!
Today I came across a requirement where I needed to select an isLoading flag from my store (that also uses ngrx/entity), and then update some data when isLoading was set to 'Loaded'. Seemed like a simple task. I'm newer to NgRx, but I've been using RxJs for 7+ years.
The code I was using:
The first time everything ran through the pipe, it worked flawlessly. My subscribe method was called after my data was loaded from the server successfully. However, when a change to one of my store entities occurred, my isLoading was being set to 'Loading', but my subscribe function was still getting called, even though it didn't pass the filter operator! As you can see from the screenshot, the filter operator wrote to the console that isLoading was 'Loading', but I had still hit my breakpoint in the subscribe when I didn't think I should:
After hours of debugging why this was happening, and pulling all of my hair out, I finally realized what the problem was... Since the entity in question had been updated (because of ...state in the reducer), the switchMap was emitting a new value. In order to avoid getting values from the switchMap when I didn't want them, I needed to add take(1) to my switchMap select:
I felt like I was living the programming meme where my build was failing because I missed a semi-colon... It's a simple thing, yet took me so long to figure out what was wrong! I'm leaving this here just in case anyone has a similar problem in the future. Maybe I can save them hours of debugging and hair pulling.
Beta Was this translation helpful? Give feedback.
All reactions