How to apply multiple filters using Redux Toolkit
P粉600845163
P粉600845163 2024-02-21 17:03:42
0
1
422

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粉600845163
P粉600845163

reply all(1)
P粉978742405

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template