Creating a cart summary component
To further demonstrate the benefits of centralized store state and getters, we're going to add a cart summary component that displays in a popup when a user hovers over the cart link in the navbar. We'll add another getter that calculates the total number of items in the cart, then use it along with the one we already have inside the popover to show how useful it is to have reusable calculated properties like this.
Add the following exported function to the ClientApp/store/getters.js
file:
exportconstshoppingCartItemCount=state=> { constreducer= (accumulator, cartItem) =>accumulator+ cartItem.quantity; returnstate.cart.reduce(reducer, 0); };
This is very similar to the previous getter we created, so it should look fairly familiar, but ultimately we're doing the equivalent of a Sum
calculation on a LINQ collection in C#. The total number of items in the cart is equal to the sum of the cart item quantity
values.
Next, create a new empty component...