Blog>
Snippets

Chaining Multiple createSelector Functions

Showcase how to chain createSelector functions to first filter a list of products by category and then calculate the average price.
import { createSelector } from '@reduxjs/toolkit';

// Selector to get the products list from the state
const selectProducts = state => state.products;

// Selector to get the category filter from the state
const selectCategoryFilter = state => state.categoryFilter;

// First createSelector: filters the products by the selected category
const selectProductsByCategory = createSelector(
    [selectProducts, selectCategoryFilter],
    (products, categoryFilter) => products.filter(product => product.category === categoryFilter)
);

// Second createSelector: calculates the average price of the filtered products
const selectAveragePriceInCategory = createSelector(
    [selectProductsByCategory],
    filteredProducts => filteredProducts.reduce((total, product) => total + product.price, 0) / filteredProducts.length
);
This code defines two selectors using the createSelector function from Redux Toolkit. The first selector, selectProductsByCategory, filters the products in the state by a category filter. The second selector, selectAveragePriceInCategory, computes the average price of the products that were filtered by the first selector.