0

I am trying to write a handleSubmit function which supposed to push an object into array users. And I wrote console.log and alert to check whether I write correctly the setUsers. However, it doesn't seem working. Would you help me where should I start to fix it? Thanks.

My current output on the console is below, but I would like to see

[ { First: "Kim", Last: "Nolan", Phone: "1234567890" } ]

{
  "users": [
    {
      "First": {
        "first": "Kim"
      },
      "Last": {
        "last": "Nolan"
      },
      "Phone": {
        "phone": "1234567890"
      }
    }
  ]
function PhoneBookForm({ addEntryToPhoneBook }) {
  const [first, setFirst] = useState('');
  const [last, setLast] = useState('');
  const [phone, setPhone] = useState('');
  const [users, setUsers] = useState([]);

  function handleSubmit(e){
    e.preventDefault();
    setUsers([...users, {
      First: {first},
      Last: {last},
      Phone: {phone}
    }]);
    console.log(users);
  }

  return (
    <form onSubmit={handleSubmit} style={style.form.container}>
      <label>First name:</label>
      <br />
      <input 
        style={style.form.inputs}
        className='userFirstname'
        name='userFirstname' 
        type='text'
        placeholder='Coder'
        onChange={e => setFirst(e.target.value)}
      />
      <br/>

      ...

      <br/>
      <input 
        style={style.form.submitBtn} 
        className='submitButton'
        type='submit' 
        value='Add User'
      />
    </form>
  )
}
ny195
  • 1
  • 1
  • It's working, you just have your log statement in a spot where it isn't useful. `users` is a local const, and it will not be changed when you call `setUsers`. So the log and alert will always show the old values. What `setUsers` does is ask react to rerender the component. When that render happens, a new local variable will be created with the new value. If you'd like to verify that the component is rerendering, put your log statement in the body of the component. – Nicholas Tower Dec 13 '21 at 20:55

0 Answers0