This lesson is pretty straightforward but demonstrates how we're combining data from two different redux slices in a single component. We have product data from the productsSlice
and shopping cart information from the cartSlice
. Neither of these is sufficient on its own, so it requires us to combine them at render-time. It's pretty common to have 5 or 6 selector functions at the top of a large component.
Note: One thing missing from the lesson is that our <tr>
element needs a key={id}
to ensure React handles updates properly. You'll likely see a warning in your console about this.
Jamund Ferguson: [0:00] Our Shopping Cart page is currently full of fake data. None of the products listed are even products available in our store. Let's fix that.
[0:07] Open up the Cart.tsx file in your IDE. Import useAppSelector from app/hooks. At the top of your Cart component, type const products = useAppSelector(state => state.product.products). Below that, type const items = useAppSelector(state => state.cart.items). We're going to use these two Redux powered values to populate our Shopping Cart page.
[0:32] Down in the body of our shopping cart, type {Object.entries(items).map}. We're going to pass in an arrow function where we destructure two values off of Object.entries, id and quantity. For that function, we're going to use parentheses to directly return JSX from our function body where it currently says Magnifying Glass. We're going to say {products [id] .name}.
[0:59] We'll do the same thing in other places. We'll do the same thing for price here. Down here where there's a label, you can actually use curly brackets and template literal and say Remove ${{products [id] .name}} from Shopping Cart. Up here in our input field, instead of default value 21, let's actually use the quantity value that we get from our map.
[1:21] If you haven't used Object.entries before, it takes an object and splits it into an array of arrays. Each key-value pair inside your object will be an array with the key as the first item and the value as the second item in the array. We're just looping over those arrays and converting them into JSX.
[1:39] Now, let's get rid of our unused mock data here. Let's go back to our Shopping Cart. It's now empty. Let's add some bananas, headphones, a couple of candles. You can see that they're all correctly being displayed in our Shopping Cart.