Why and when you should use NgRx Data?
The aim of this article is to show how to use NgRx Data and why you should do it. NgRx Data is an extension of NgRx state management system for angular framework. The advantage of using NgRx Data is simplicity and a drastic code reduction in compare to traditional approach. Of course the world isn’t perfect and you can’t use this extension everywhere. Quoting NgRx Data documentation, typical usage of this library is entity data management. Basically it means that if you have complex entity collection you should go hard way and use @ngrx/entity where the boilerplate code is huge.
At first I will show you how easy is to create NgRx Data store. We will work on delivery app with fake backend. After that I will drop a few lines about limitation of this approach 😁. Below you can find an example app on stackblitz, that I created in order to understand the problem. Soo no more introductions let’s start coding 😎💪.
Mechanism behind this application is very simple. When you click on three dots you can change the state of delivery and this is update on NgRx data store and PUT on the backend. Under those three dots you can also delete delivery (DELETE on store and on backend). When you click + button on footer you will add delivery and trigger POST and Add on store. You can switch between deliver and undelivered tabs by pressing clock and thumb up button.
Configuration of NgRx Data store is very simple and when I did it for the first time I was in big shock.
First you should create a model :
Next configure a service:
Last create EntityMetadataMap and add it into NgModule:
That’s it 🖖. Now you can add, remove, get and update LunchSpot objects. It is worth to mention that you must configure core address of your endpoint in provider . Like in line 20.
The usage is even easier:
Basically add service to the constructor and use getAll, add, update and delete. If you want to view lunchSpots objects on UI just use this.deliverySpots$ = this.deliveryService.entities$;
Of course because of the huge amount of automation you lose control over your code. This force you to do everything by the book:
- You must always map store update to PUT.
- When you use delete all parameters are in params not in the body
- When you use GetAll() endpoint must be in plural
- All names of the endpoint are taken from name of entity
You can find here full list of limitations that are exist in NgRx Data. Please look carefully before making decision to use this framework in your app.
Generally I recommend NgRx Data to very small apps or in hybrid approach where you use NgRx Data to simple objects and NgRx Entity to complex list of entities.
I hope that you will like my app and that this article will help you to start with NgRx Data. In case of any trouble don’t hesitate to write comment, I will try to help 😏.