Z
Z
zlodiak2020-11-01 17:54:04
JavaScript
zlodiak, 2020-11-01 17:54:04

How to write states to an object?

The state of the login form is controlled by the useState hook. Each form field has an onChange handler. Upon 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 in the login field in the state, the password values ​​disappear. And when the password field is filled in the state, the login values ​​disappear. This is visible on the screen:
{ form.login }--
{ form.password }


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

There is an option to use two useState hooks, but I need exactly one

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tigran Abrahamyan, 2020-11-01
@zlodiak

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

K
Kirill Makarov, 2020-11-01
@kirbi1996

Yes, that's right, you are overwriting the state, so you need to use the spread operator to save the old field values. As stated in the answers above. From myself, I can add something 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.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question