Blog>
Snippets

Implementing User-defined Filters

Demonstrate how to use `createReducer` for managing the state of user-defined and dynamically added filters in a search interface.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Define actions for adding and removing filters
const addFilter = createAction('filters/add');
const removeFilter = createAction('filters/remove');

// Initial state
const initialState = {};

// Reducer managing the state of filters
const filtersReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(addFilter, (state, action) => {
      // Add a new filter with a unique identifier
      const { id, filter } = action.payload;
      state[id] = filter;
    })
    .addCase(removeFilter, (state, action) => {
      // Remove a filter by its identifier
      const { id } = action.payload;
      delete state[id];
    });
});

export default filtersReducer;
This code defines actions and a reducer for managing a dynamic set of user-defined filters. The 'addFilter' action adds a new filter to the state, while the 'removeFilter' action removes a filter by its identifier. The initial state is an empty object, allowing filters to be keyed by unique identifiers.