Appointment Project

[Appointment Project]

I’ve been stuck on adding a contact to the contacts array ultimately a new contact is added but name, phone, and email are all undefined thanks for all your help. When I console.log(newContact) it returns the correct information but when it is returned back to onAdd everything is undefined I passed the addContact function via onAdd to the Contacts Page here is my addContact function in App.js:

const addContact = (id, name, phone, email) => {
 
  const contact = {
    id: id,
    name: name,
    phone: phone,
    email: email
  }
  return setContacts((prevContacts) => [...prevContacts, contact]);
}

Here I’m rendering ContactPage.js:

 <ContactsPage onAdd={addContact} data={contacts}/>

And inside ContactPage.js (I know there may be other errors but I’m only concerned with adding a contact at this point):

export const ContactsPage = (props) => {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');
  const [duplicate, setDuplicate] = useState(false);
  const {data, onAdd} = props;


  const handleSubmit = (e) => {
    e.preventDefault();
    /*
    Add contact info and clear data
    if the contact name is not a duplicate
    */
    let newContact = {
      id: Date.now(),
      name: name,
      phone: phone,
      email: email
    }
    console.log([newContact])
    if(duplicate === false) {
      onAdd((prev) => [newContact, ...prev]);
      alert("New contact added");
      clearForm();
    } else {
      alert("Contact is a duplicate");
      }
  
    }
    
    const clearForm = () => {
      setName('');
      setPhone('');
      setEmail('');
      setDuplicate(false);
    }
    
    useEffect(
      () => {
      if(!data.filter(contact => contact.name !== name)) {
          setDuplicate(true);
        }
      }, [name, data])

  /*
  Using hooks, check for contact name in the 
  contacts array variable in props
  */
  return (
    <div>
      <section>
        <h2>Add Contact</h2>
        <ContactForm
        name={name}
        setName={setName}
        phone={phone}
        setPhone={setPhone}
        email={email}
        setEmail={setEmail}
        handleSubmit={handleSubmit}
        />

I figured out my problem in App.js by passing the entire object to addContact then grabbing the props when creating the contact. Example below.

const addContact = (newContact) => {
 
  const contact = {
    id: newContact.id,
    name: newContact.name,
    phone: newContact.phone,
    email: newContact.email
  }
  return setContacts((prevContacts) => [...prevContacts, contact]);
}

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.