0

I am working on a simple react app where I would like to prevent the form from adding a duplicate element to the array of objects

I have two instances of state

 const [persons, setPersons] = useState([
    { name: 'Arto Hellas' }
  ]) 
 const [newName, setNewName] = useState('')

a function that sets the new name upon input change

 function handleNoteChange(e){
console.log(e.target.value)
setNewName(e.target.value)
  }

and a function that intends to add a new element to the array upon submission of the form

function addName(e){
     const newNameObject = {
       name: newName
     }
     console.log(persons.includes(newNameObject))
     e.preventDefault()
     setNewName("") 
if(persons.includes(newNameObject) ){
  alert(`${newName} has already been added`)
  
}
else{
  setPersons(persons.concat(newNameObject))
}
  }

I have a console.log where I am checking to see if the current name I am inputing ('Arto Hellas') is already in the persons array, its saying this is false when it should be true since this is the first and only item in my state so far, not sure exactly why this is happening

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
mattangel
  • 71
  • 4
  • 3
    _Another_ object with the same contents exists in the array, but not the _same_ object. – CherryDT Jan 27 '23 at 06:09
  • `includes` can't do object comparisons because they're _two different objects_ and will never be comparable - object comparisons don't work like that in JS at all. You'll have to check for the name first, and _then_ build the object. – Andy Jan 27 '23 at 06:10

1 Answers1

1

It is returning false, because includes does comparison based on reference not on the value that each object holds.

To solve your use case, you have to manually iterate through each object in the array and do object comparison with the required element as show below.

function containsObject(searchElement, actualArray) {
    var isObjectPresent = true;
    for(var i = 0; i < actualArray.length; i++) {
        if(JSON.stringify(actualArray[i]) != JSON.stringify(searchElement)) {
            isObjectPresent = false;
            break;
        }
    }
    return isObjectPresent;
}

NOTE: This approach works only if the order of the properties are same