WapShivam
WapShivam

Reputation: 964

Delete multiple item from array - Redux State

I'm working on react app with redux. I want to delete multiple item from array. I write below code in my reducer which delete single item from array but i want to delete multiple item.

case DELETE_LINK:  
    let dltLink = state.filter(item => {
            return item._id !== action.data._id

    }) 
    return {
        ...state,
        parentFolderlinks: dltLink
    };

Upvotes: 0

Views: 1206

Answers (3)

Suman Kharel
Suman Kharel

Reputation: 1090

On what basis would you like to filter items? I assume that multiple items will not have the same id.

Below example shows how we can filter multiple items in redux. In this case, foods state with items that has type as fruit and removes everything else.

// initial state with all types of foods
const initialState = {
    "foods": [
        {
            name: "apple", 
            type: "fruit"
        }, 
        {
            name: "orange", 
            type: "fruit"
        }, 
        {
            name: "broccoli", 
            type: "vegetable"
        }, 
        {
            name: "spinach", 
            type: "vegetable"
        }, 
    ]
}

// sample reducer that shows how to delete multiple items 
export default (state = initialState, { type, payload }) => {
    switch (type) {
    
    // delete multiple items that does not have type fruit
    // i.e both brocolli and spinach are removed because they have type vegetable
    case DELETE_ITEMS_WITHOUT_TYPE_FRUIT:
        const onlyFruits = state.foods.filter(food => food.type === "fruit");

        return {
            ...state, 
            foods: onlyFruits
        }
    }
}

Upvotes: 1

Murillo
Murillo

Reputation: 1173

It seems you want to filter links from state.parentFolderlinks, say you have the ids in action.data.ids, you could

case DELETE_LINK:
    const parentFolderlinks = state.parentFolderlinks.filter(item => {
            return !action.data.ids.includes(item._id);
    });
    return {
        ...state,
        parentFolderlinks
    };

Upvotes: 1

Red Baron
Red Baron

Reputation: 7642

you could map over the state and run it through a function that works out if you want to keep it or not (I don't know what your logic is for that) then return the array at the end

const keepThisItem =(item) => {
   return item.keep
}

case DELETE_LINK:
    let itemsToKeep = []  
    let dltLink = state.map(item => {
        if(keepThisItem(item){
            itemsToKeep.push(item)
        }
        return itemsToKeep
    }) 

Upvotes: -1

Related Questions