0

I have a WordPress Gutenberg block that I'm able to add items to an array in. However, I need to provide the user a way to remove a specific list item from the array of items when clicking a button next to the specific item. The data is stored as an array of objects. Outside of WordPress and Gutenberg, this will work on a basic level of removing an item by index from an array. However, the following not only doesn't remove an item, it is also blocking adding new items.

Markup used to trigger delete function

{items.map((item, index) => {
    return (
        <Button
        onClick={removeElement(index)}
        />
        <RichText.Content
            value={item['listItem']}
        />
    )
})}

Used to add new empty item to list

const addListItem = () => {
        setAttributes({
            items: items.concat({
                listItem: ''
            })
        });
    };

How I'm currently attempting to remove the selected object from the array

const removeListItem = index => {
        items.splice(index, 1);
        return items;
    };

I have seen suggestions of using array.filter, but will not remove the index from the array.

Josh
  • 17,834
  • 7
  • 50
  • 68
user3438917
  • 417
  • 1
  • 7
  • 26
  • did you visit this? https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array – bakar_dev Jul 13 '20 at 13:25
  • It looks like react.js tag is missing here. If so, you shouldn't mutate state directly with `.splice()`, at the very least, you should do shallow copy of `items` beforehand. Furthermore, deleting items by index may not be such a good idea, since state updates are asynchronous and by the time it comes turn to delete array item, your index may be pointing to totally different item. However, `.filter()`-based approach would be something, like `setAttributes({items: items.filter(_,i) => i != index)})` – Yevhen Horbunkov Jul 13 '20 at 13:46

0 Answers0