Using Immer with Entity in NgRx
Aart den Braber
Ik ben een freelance dev bij DUO met een passie voor mooie code en onderhoudbare applicaties
Entities are a great pattern in NgRx that take a lot of work out of your hands and makes managing collections very easy.
This short post is not to explain what NgRx Entity is. If you're not sure, please check out the following link.
Here we go
Instead of setting your store fields with something like this
You could use NgRx Entity, which really simplifies your life a lot. Notice the lack of the `collection` field in the below example. If you're not sure how this works, please check out the link above ?.
However, we still have to spread the state (using `...state`, which gets even messier when you have nested dictionaries) to make sure the rest of the state is updated. For this, we should use Immer. Check out this link if you're not sure what Immer is.
To do this, use code like this:
We can easily change the draft, which Immer updates the state with. In this example, I made use of a very simple store, but check out what happens if we use a more complicated one.
Immer is the way to go for most (if not all) use-cases, I believe. It adds safety and simplicity. ??
Do you have a better idea or did it help you? Let me know!
Tags: NgRx, entity, entities, adapter, Immer, immutability, immutable, typesafe