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 inputting ('Arto Hellas') is already in the person 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