How do I write states to an object?

  • 0
    The state of the login form is controlled using the useState hook. An onChange handler is hung on each form field. After user input, the corresponding values ​​are written to the state object:

    import React, { useState } from 'react';
    
    function Auth(props) {
      const [form, setForm] = useState([{
        login: '',
        password: '',
      }]);
    
      return (
        <>
          <div className="login-form">
            <input type="text" onChange={ e => { setForm({ login: e.currentTarget.value }) } }/>
            <br/>
            <input type="text" onChange={ e => { setForm({ password: e.currentTarget.value }) } }/>
            <br/>
            <button>auth</button>
            { form.login }--
            { form.password }
          </div>
        </>
      );
    }
    
    export default Auth;


    The problem is that after filling the login field in the state, the password values ​​disappear. And when filling in the password field in the state, the login values ​​disappear. This can be seen on the screen:
    { form.login }--
    { form.password }


    Please help me to make sure that the values ​​of both fields are saved independently in the state.

    There is an option to use two useState hooks, but I need just one
    JavaScript Lorelei Sherman, May 30, 2020

  • 3 Answers
  • 0
    <input type="text" onChange={e => setForm({ ...form, login: e.target.value })} />
    <input type="text" onChange={e => setForm({ ...form, password: e.target.value })} />
    Anonymous

  • 0
    const [ form, setForm ] = useState({
    login: '',
    password: '',
    });

    const onChange = ({ target: t }) => setForm({ ...form, [t.name]: t.value });


    <input name="login" value={form.login} onChange={onChange} />
    <input name="password" value={form.password} onChange={onChange} />
    Anonymous

  • 0
    Yes, that's right, you are overwriting the state, so you need to use the spread operator to keep the old field values. As stated in the answers above. From myself, I can add that it would not be bad to immediately use the react-hook-form library. It will reduce the number of renders, which will have a good effect on performance.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!