search

Home  >  Q&A  >  body text

How to apply multiple filters using Redux Toolkit

I'm trying to filter data by categories such as type, brand, color, gender using Redux Toolkit. Filters work individually, but filters don't work together. If I filter out the brand first and then filter out the color, the brand filter doesn't work. What do I need to do to make this work?

const initialState = {
    products: data,
    filteredItems: data,
}

export const filterSlice = createSlice({
    name: "filter",
    initialState,
    reducers: {
        filterCategory: (state, action) => {
            if (action.payload === "All") {
                return initialState
            } else
            state.filteredItems = state.products.filter(
                (item) => item.category === action.payload
            ) 
        },
        filterGender: (state, action) => {
            state.filteredItems = state.products.filter(
                (item) => item.gender === action.payload
            ) 
        },
        filterColor: (state, action) => {
            state.filteredItems = state.products.filter(
                (item) => item.color === action.payload
            )
        },
        filterBrand: (state, action) => {
            state.filteredItems= state.products.filter(
                (item) => item.brand === action.payload
            )
        },
    }
})

I tried writing the filter in a reducer but it still doesn't work

P粉600845163P粉600845163319 days ago475

reply all(1)I'll reply

  • P粉978742405

    P粉9787424052024-02-22 10:06:57

    I might do something similar

    const initialState = {
        products: data,
        filteredItems: data,
        filters: {}
    }
    
    reducers: {
        filterCategory: (state, action) => {
            if (action.payload === "All") {
                return initialState
            } else {
                state.filters = { ...state.filters, category: action.payload }
                state.filteredItems = state.products;
            ) 
        },
        // ...etc.
        Object.entries(state.filters).forEach(([key, value]) => {
            state.filteredItems = state.filteredItems.filter(
                (item) => item[key] === value
            );
        });
        return state;
    }

    so that you save which filters are active and then set filteredItems to the full list of items and then apply each filter individually.

    reply
    0
  • Cancelreply