Composing Selectors
Demonstrate the composition of multiple selectors to calculate a more complex piece of state, highlighting how to build on simpler selectors.
import { createSelector } from '@reduxjs/toolkit';
// Simple selector to get the list of products from state
const selectProducts = state => state.products;
// Simple selector to get the category filter value
const selectCategoryFilter = state => state.categoryFilter;
// Composed selector to get filtered products by category
const selectFilteredProducts = createSelector(
[selectProducts, selectCategoryFilter],
(products, categoryFilter) => products.filter(
product => product.category === categoryFilter
)
);
Defines two simple selectors: one for retrieving the products list and another for getting the current category filter. Then, a composed selector is created using `createSelector` from Redux Toolkit to acquire the filtered list of products based on the selected category.
// Another composed selector combining user data and order history
const selectUserData = state => state.user.data;
const selectUserOrders = state => state.orders.userOrders;
const selectUserOrderHistory = createSelector(
[selectUserData, selectUserOrders],
(userData, userOrders) => ({
name: userData.name,
orders: userOrders
})
);
Sets up additional simple selectors for user data and user's order history. It then composes a more complex selector that combines these two pieces of state to create a user object with both name and order history.