Composing Selectors for Complex Calculations
Provide an example of composing multiple selectors with createSelector to compute a derived state that depends on different parts of the store.
import { createSelector } from '@reduxjs/toolkit';
// Input selector: gets the products from the state
const selectProducts = state => state.cart.products;
// Input selector: gets the quantities from the state
const selectQuantities = state => state.cart.quantities;
// Selector that computes the subtotal of each product
const selectSubtotals = createSelector(
[selectProducts, selectQuantities],
(products, quantities) => products.map(product => product.price * (quantities[product.id] || 0))
);
// Selector that computes the total cart value
const selectCartTotal = createSelector(
[selectSubtotals],
(subtotals) => subtotals.reduce((total, value) => total + value, 0)
);
This set of selectors calculates the total cart value from a Redux state. The first two selectors retrieve parts of the state related to products and quantities. The 'selectSubtotals' selector calculates the subtotal for each product by multiplying its price with the quantity. Lastly, 'selectCartTotal' uses these subtotals to compute the overall total value of the cart.