Why is my console log persons includes newNameObject returning as false when newNameObject already exists in the array

0 votes

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

Jan 27, 2023 in Others by Tejashwini
• 3,820 points
312 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.

Related Questions In Others

0 votes
1 answer
+1 vote
1 answer

Why is the result distorted when we use threads?

A thread is basically a part of ...READ MORE

answered Jun 6, 2019 in Others by Nisa
• 1,090 points
919 views
–2 votes
0 answers
0 votes
1 answer

Why is just an ID in the URL path a bad idea for SEO?

yes it affects the click through rates ...READ MORE

answered Feb 20, 2022 in Others by narikkadan
• 63,680 points
502 views
0 votes
0 answers

How do I determine the size of my array in C?

How do I determine the size of ...READ MORE

May 1, 2022 in Others by Kichu
• 19,050 points
438 views
0 votes
0 answers
0 votes
1 answer

How to store an array in localstorage?

Localstorage only supports Strings. So you can ...READ MORE

answered Jul 1, 2019 in Others by sunshine
• 1,300 points
22,977 views
0 votes
1 answer

Error:Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

Hello @kartik, It is happening because any where ...READ MORE

answered Jun 4, 2020 in Angular by Niroj
• 82,880 points
2,428 views
0 votes
1 answer

Error:setState doesn't update the state immediately

Hello @kartik, The method setState() takes a callback. And ...READ MORE

answered Jun 4, 2020 in Angular by Niroj
• 82,880 points
5,095 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP