3

I'm using React js. I want to add an option to delete multiple items. but after deleting each item, page refreshes the props and not delete remaining items.

How can I delete Multiple items?

const onDeleteAll = arr => {
        
    arr.forEach(element => {
      const formData = {
        id:element
      }

      props.onDeleteSubmit(formData, function(){ // pass id to delete func
        console.log('deleted')
      })
    });
  }
  useEffect(() => {
    props.getPriceType(); // fetching data
  }, []);

reducer:

case DELETE_PRICE_TYPE_SUCCESS_ACTION:
          const myDeletedArray = draft.list;
          const objDeletedIndex = myDeletedArray.filter(obj => obj.id !== action.payload._id);
          draft.list = objDeletedIndex; //update data
          break;
kinza
  • 225
  • 2
  • 9

2 Answers2

3

var id = 23;
var list = [{
  id: 23,
  value: "JOHN"
}, {
  id: 23,
  value: "JADE"
}, {
  id: 24,
  value: "JADE"
}, {
  id: 25,
  value: "JAMES"
}];

var indexes = [];
const templist = list.filter((item, ind) => {
  return item.id !== id
});
list = templist;
console.log(list);

First get the list of indexes which matches the items in the array to be deleted. Traverse the above list and delete the items from each array by splice operator.

Asutosh
  • 1,632
  • 2
  • 13
  • 21
1

I think the problem is that you have multiple items to delete, but you trigger a delete action for only 1 at a time. You need to collect all the ids to delete in a list, and send that list to the action, and in reducer just filter that ids.

const onDeleteAll = arr => {

  //this just to follow your current shape of things
  //ideally you don't want to do that, just pass arr to the onDeleteSubmit

  const formData = arr.map(element => ({
      id:element
  }));

  props.onDeleteSubmit(formData, function(){
      console.log('deleted')
  })  
  
}
useEffect(() => {
  props.getPriceType(); // fetching data
}, []);

reducer:

case DELETE_PRICE_TYPE_SUCCESS_ACTION:
          const myDeletedArray = draft.list;
          const objDeletedIndex = myDeletedArray.filter(obj => 
            !action.payload.find(itemToDelete=>itemToDelete._id===obj.id)
          );
          draft.list = objDeletedIndex; //update data
          break;
dulebov.artem
  • 706
  • 1
  • 4
  • 14