Blog>
Snippets

Reselect with Multiple Arguments

Provide an example of using createSelector with multiple arguments to select data based on multiple pieces of state.
import { createSelector } from 'reselect';

// Input selector that retrieves the items from the state
const selectItems = state => state.items;
// Input selector that retrieves the filter criteria from the state
const selectFilter = state => state.filter;

// Memoized selector that filters items based on the filter criteria
const selectFilteredItems = createSelector(
  [selectItems, selectFilter],
  (items, filter) => items.filter(item => item.category === filter.category)
);

// Usage example:
// Assuming our state looks something like this:
// const state = { items: [{ id: 1, category: 'books' }, { id: 2, category: 'movies' }], filter: { category: 'books' } };

// Get the filtered items
const filteredItems = selectFilteredItems(state);
console.log(filteredItems); // Should output: [{ id: 1, category: 'books' }]
This example imports createSelector from 'reselect' and sets up two input selectors: one to retrieve items from the state, and another to retrieve filter criteria. A memoized selector called selectFilteredItems uses both input selectors to filter items based on category. The usage example assumes a given state shape and demonstrates calling the memoized selector to obtain filtered items.