I have my application in React, something simple in my opinion, but the problem I have is that when I want to add an empty contact, be it a phone number or a name, it appears that this contact already exists, I don't understand why since I have a line of code which searches if that contact name only exists or not, but I don't understand if those fields are empty because it recognizes it as already existing.
My filter only matches the name, the number can be the same.
Lines of code where I add a contact
If the contact to add has the name of an existing contact in the database, a message pops up that says if I want to update the phone number, but if an empty contact is added, the same message pops up and I don't understand why.
const addContact = (event) => {
event.preventDefault();
const personInfo = {
name: newName,
number: newNumber
};
// const duplyPerson = (persons.map(person => person.name));
const findPerson = persons.find(personData => personData.name.includes(newName));
const changedNumber = {...findPerson, number: newNumber};
console.log(findPerson);
if (findPerson) {
if (window.confirm(`${newName} is already added to phonebook, replace the old number with a new one?`)) {
personsService.updatePersonPhone(findPerson.id, changedNumber).then(returnedPersons => {
setPersons(persons.map(note => note.id !== findPerson.id ? note : returnedPersons));
setNewName('');
setNewNumber('');
});
}
} else {
personsService.savePerson(personInfo)
.then(savePersonInfo => {
setPersons(persons.concat(savePersonInfo));
setNewName('');
setNewNumber('');
});
}
};
full application
You could change your logic so that when you look for the person in question you do it by index and if the index matches then the if proceeds to execute, otherwise it would save your contact normally. Here is the part of the code that you should change.