Search code examples
javascriptreactjsdrag-and-dropreact-dnd

Removing an item from React-dnd


I have created my own example off of this React-dnd example to create the drag and drop. I have added a Card which can use onRemove function to remove a card. Even when Im clearing out the state array with all the objects I dont see the removal effect.

My removal function:

const handleRemove = useCallback(
(index, item) => {
  // Delete a value if found, all occurrences
  update(dustbins, {
    items: (dustbins) =>
      dustbins && dustbins.filter((arrItem) => arrItem !== item)
  });

  if (dustbins && dustbins.includes(item) && index >= 0) {
    update(dustbins, { lastDroppedItem: { $splice: [[index, 1]] } });
  }

  // Delete at a specific index, no matter what value is in it
  //   update(dustbins, { lastDroppedItem: { $splice: [[index, 1]] } });
},
[dustbins]
  );

dustbins received in this method are constantly undefined and not sure why though. which basically doesnt run the rest of the statements in this method. What am I doing wrong here?

Another challenge I am facing here is that I can drag and drop an item but this solution creates duplicates. I tried using $splice function but that doesnt work as Dustbin.jsx uses drop: onDrop, method to handle drop functionality. How can I remove the duplicates?

Thanks


Solution

  • And I finally made it work. So I can answer my own question here.

    Im using immutabilityHelper function $set which is similar to a normal set function.

       const indexOf = useCallback(function indexOf(array, item) {
        for (var i = 0; i < array.length; i++) {
          console.log("Arr", array[i]);
          if (
            array[i].lastDroppedItem &&
            array[i].lastDroppedItem.name === item.name
          )
            return i;
        }
        return -1;
      }, []);
    
      const handleRemove = useCallback(
        (item) => {
          const index = indexOf(dustbins, item);
          console.log("LastDroppedItem Index", index);
          if (index < 0) return;
          setDustbins(
            update(dustbins, {
              [index]: {
                lastDroppedItem: {
                  $set: null
                }
              }
            })
          );
    

    Im first finding an index and then setting a null on lastDroppeditem on that index. Hope it helps others. Link to the working source.