Using Immer with Entity in NgRx
Simplicity by uxing entities and Immer

Using Immer with Entity in NgRx

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

No alt text provided for this image

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 ?.

No alt text provided for this image

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:

No alt text provided for this image

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.

No alt text provided for this image

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

要查看或添加评论,请登录

Aart den Braber的更多文章

社区洞察

其他会员也浏览了