Search code examples
javascriptarraysreactjssplice

How to delete an element from array in react?



I have two functions , one of them adds an item in array and the other one delete from that array using React JS (hooks).[Both are handler of click event].
What I have works incorrectly.
``id`` comes from ``contact.length`` and I deleted it with``contacts.splice(id, 1)``.
I dont have any idea why it has this problem.
it doesnt delete what would be clicked but a random one.
function handleAddRecord(nameValue, phoneValue) {
        setContacts([...contacts , {
            id : contacts.length,
            name : nameValue,
            phone : phoneValue
        }])
    }
    

    function handleDelete(id) {
        console.log("manager", id);
        const newContacts =  contacts.splice([id],1);
        setContacts([...newContacts]);
    }

Solution

  • One of the issue on the implementation is id generation keeping it array length could lead to issue as you delete and add elements there could be scenarios where there is same id for multiple items.

    One of most widely used generator is uuid https://www.npmjs.com/package/uuid

    Usage

    const uuid = require("uuid");
    uuid.v4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
    

    Now use this in your implementation

    Add Operation:

    const handleAddRecord = (nameValue, phoneValue) => {
      const newRecord = {
        id: uuid.v4(),  // This should be unique at all times
        name: nameValue,
        phone: phoneValue,
      };
      setContacts([...contacts, newRecord]);
    };
    

    Delete Operation:

    Use filter rather than splice as for splice you'll need to find the index of the element with id. But with Filter it can be done is a single line

    const handleDelete = (id) => {
      setContacts(contacts.filter(item => item.id !== id));
    };