In this lesson we take data from two different slices and combine the output in a single selector function. Because selectors get access to the entire RootState
it's not hard to create these combinations. The other thing that's interesting here is that we're passing multiple input selectors into createSelector
. You can read more about how that works below.
createSelector
was brought in to RTK from the popular reselect library. While it's not needed to create selector functions, it makes it a lot easier to create efficient selectors that avoid doing more work than needed.
createSelector
takes two types of arguments. There are inputSelectors
(and there can be more than one of these) and then there's the resultFunction
. You pass in these input selectors and then the result function processes the data that gets returned. As long as the input values don't change, the generated selector won't re-run the result function.
If the data you're working with isn't large or the calculations aren't complex, you don't really need to use createSelector
. But it's a good tool to have in your toolbox.
Check out this link for more info: https://github.com/reduxjs/reselect#createselectorinputselectors--inputselectors-resultfunc
Jamund Ferguson: [0:00] Open up cartSlice.ts, and at the bottom of the file type export const getTotalPrice = createSelector(). This time we're going to pass in three functions.
[0:12] The first one is going to take state of type RootState and return state.cart.items. The second one is also going to take in state and return state.products.products. Lastly, we're going to pass in a function that takes in items as its first argument and products as its second. Here, we're going to calculate the total value of all the products in your shopping cart.
[0:35] Type let total = for (let id in items) { total += products [id] .price * items[id] }. This is the price of an individual item times the number of items you have in your cart. Then, we're going to return total.toFixed(2). This will essentially round us to the nearest two decimal places. We've just created a selector that relies on two pieces of state rather than one.
[1:03] Inside of Cart.tsx, we are going to import { getTotalPrice } from "./cartSlice" and at the top of the page const totalPrice = useAppSelector(getTotalPrice). Then, down at the bottom of the file where we have hard-coded ., let's put in totalPrice.
[1:24] If we go to our Shopping Cart now, it's currently . Let's add some bananas, some chocolates. You can see that our total is now calculated properly.