Retr0A
Retr0A

Reputation: 11

Remove an item form an array in react

I am making a Website OS in React.js, and I have a problem removing an item from an array in handleWindowRemove, it removes all other items.

This is the array code:

const [openedWindows, setOpenedWindows] = useState([
    ]);
    
    const handleWindowAdd = () => {
        setOpenedWindows([...openedWindows, { openedWindow: "" }]);
    }
    
    const handleWindowRemove = (index) => {
        const list = [...openedWindows];
        
        const i = openedWindows.indexOf(index);

        list.shift(i, 1);

        setOpenedWindows(list);
        //alert(index);
    }

Github Repository

Upvotes: 1

Views: 534

Answers (3)

B.Anup
B.Anup

Reputation: 585

  1. If you are dealing with a list of array elements, using an index for identifying an element to perform some operation, especially delete is not recommended at all.

  2. Since you are passing 'index' as an argument for 'handleWindowRemove', I am assuming you are using 'index' as a key while rendering the list of elements. Whenever you perform an delete operation on element using "splice" or any other method using 'index', it will result in change of index of other elements present in Array too. If you are using index as key while rendering list of array elements, everytime you delete an item in Array using index, index of remaning elements will change and cause re-rendering of almost all the elements present in array. This is not the recommended approach since it will re-render the elements that are not modified.

  3. Better approach would be having 'id' properties for all the objects of Array. In this approach, 'id' can be used as a key while rendering and also as an identifier while deleting the object from the array. Due to this, other window objects won't be affected. Hence re-rendering of unmodified objects will not happen.

    const openedWindows = [{'id': # identifier, 'windowObject': ...}]
    

Upvotes: 0

Hyetigran
Hyetigran

Reputation: 1215

Shift method is supposed to remove the first element of the array and does not take any arguments. You could use the splice method instead.

However, I find filter method works best here:

const handleWindowRemove = (index) => {
        const updatedList = openedWindows.filter((el, idx) => idx !== index);
        setOpenedWindows(updatedList);
    }

Upvotes: 1

Apollo79
Apollo79

Reputation: 704

I think you are looking for Array.prototype.splice.

Array.shift removes the first item of an array.

Here is a corrected example:

const [openedWindows, setOpenedWindows] = useState([
    ]);
    
    const handleWindowAdd = () => {
        setOpenedWindows([...openedWindows, { openedWindow: "" }]);
    }
    
    const handleWindowRemove = (index) => {
        const list = [...openedWindows];
        
        const i = openedWindows.indexOf(index);

        list.splice(i, 1);

        setOpenedWindows(list);
        //alert(index);
    }

Upvotes: 0

Related Questions