Good
Good

Reputation: 81

Set state using onChange using hook

I want to get the value when I change it with onChange and created a name and contact number by using the value and setContacts, this app does not cause error but it does not work, Where is the problem? Thanks.

Each new contact in an object has an id, a name and a phone number

const AddUSer = () => {
  const {contacts, setcontacts}=useState([]);
  const { userName, setUSerName } = useState("");
  const { userPhone, setUserPhone } = useState("");
  const setName = (e) => {
    const value = e.target.value;
    return setUSerName(value);
  };
  const setPhone = (e) => {
    const value = e.target.value;
    return setUserPhone(value);
  };
  const handleNewcontact = () => {
    const allcontacts = [...contacts];
    const newContact = {
      id: Math.floor(Math.random() * 1000),
      fullName: userName,
      phone: userPhone,
    };
      allcontacts.push(newContact);
      setcontacts(allcontacts);
      setUSerName("");
      setUserPhone("");
    }
  };
  return (
    <div className="container">
      <form>
        <label>Name</label>
        <input className="form-control" onChange={(e) => setName} />
        <label>Phone</label>
        <input className="form-control" onChange={(e) => setPhone} />
        <button
          onClick={handleNewcontact}
          className="btn btn-primary mt-3 mb-4"
        >
          Save
        </button>
      </form>
    </div>
  );
};

export default AddUSer;

Upvotes: 1

Views: 55

Answers (2)

Kellswork
Kellswork

Reputation: 1

try this. the values are consoled when the user clicks the submit button.

const AddUSer = () => {

const [contact, setContact] = useState({id: '', userName:'', userPhone:''});

  function handleNewContact(event) {
    setContact({
      ...contact, id: Math.floor(Math.random() * 1000),
      [event.target.name]: event.target.value
    });

  }

  function handleSubmit(event) {
    event.preventDefault();
    console.log(contact);
  }
  

  return (
    <div className="container">
      <form>

        <label>Name</label>
        <input className="form-control" name='userName' 
        onChange={handleNewContact} />

        <label>Phone</label>
        <input className="form-control" name='userPhone' 
         onChange={handleNewContact} />
        <button
          onClick={handleSubmit}
          className="btn btn-primary mt-3 mb-4"
        >
          Save
        </button>
      </form>
    </div>
  );
};

export default AddUSer;

Upvotes: 0

Sinan Yaman
Sinan Yaman

Reputation: 5937

You are not passing the event to the function. You can either do

onChange={(e) => setName(e)}
onChange={(e) => setPhone(e)}

but better:

onChange={setName}
onChange={setPhone}

Upvotes: 1

Related Questions