so i have the problem where i have the form a phonebook and i add people in it but the task is whenever i try add the user that is already in there it must not let me do it and throw an error this person is already in a phonebook i dont want only solution i want explanation if anyone can explain it to me how to solve it and how it works code:
import React, { useState } from 'react'
import Person from './Person'
const App = () => {
const [persons, setPersons] = useState([
])
const [newName, setNewName] = useState('')
const handleNoteChange = (event) => {
setNewName(event.target.value)
}
const resetForm = () => {
setNewName('')
}
const handleSubmit = (e) => {
e.preventDefault()
const persona = {
name: newName,
id:Math.floor(Math.random() * 10000)
}
setPersons(persons.concat(persona))
setNewName('')
persons.map(perperson =>{
if(perperson.name === newName){
alert(`${newName} is already in the phonebook `)
}
})
console.log(persona);
}
return (
<div>
<h2>Phonebook</h2>
<form onSubmit={handleSubmit}>
<div>
name: <input
value={newName}
onChange={handleNoteChange}
/>
</div>
<div>
<button type="submit">add</button>
</div>
</form>
<h2>Numbers</h2>
<ul>
{persons.map(person => {
return(
<Person key={person.id} name={person.name} />
)
})}
</ul>
<p onClick={resetForm}>reset input</p>
<p>phonebook name is - {newName}</p>
</div>
)
}
export default App
Person component:
import React from 'react';
const Person = (props) => {
return(
<div>
<li key ={props.id}>{props.name}</li>
</div>
)
};
export default Person;