Michael Podlevskykh
Michael Podlevskykh

Reputation: 245

The state is not updated via the useState hook the first time

The state is updated only on the next keystroke but with the previous state. Screen 1

When you click on updateForm (), it is also empty, only after the second click, the state is updated. Screen 2

I understand that this is due to asynchrony, but in this case I do not know how to use it.

Home.jsx

import React, { useState } from 'react';
import { Form } from '../components/Form/Form';

const Home = () => {
  const [dateForm, setDataForm] = useState({});

  const updateForm = eachEnry => {
    setDataForm(eachEnry);
    console.log(dateForm);
  };

  return (
    <div>
      <Form updateForm={updateForm} />
    </div>
  );
};
export default Home;

Form.jsx

import React, { useState } from 'react';
import './Form.scss';

export const Form = ({ updateForm }) => {
  const initInputState = {
    name: '',
    password: ''
  };
  const [dataForm, setDataForm] = useState(initInputState);
  const { name, password } = dataForm;

  const onChange = e => {
    setDataForm({
      ...dataForm,
      [e.target.name]: e.target.value
    });
  };

  const onSubmit = e => {
    e.preventDefault();
    updateForm(dataForm);
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <input
          type="text"
          placeholder="Name"
          value={name}
          onChange={onChange}
          name="name"
        />
        <input
          placeholder="Password"
          onChange={onChange}
          value={password}
          type="text"
          name="password"
        />
        <button type="submit">Login</button>
      </form>
    </div>
  );
};

Ввод инпута получаю данные формы в родительском компоненте

Upvotes: 0

Views: 63

Answers (2)

Nick
Nick

Reputation: 420

Your code is working fine. You just doing console.log before the state is updated. State updates happen not when you using an update state function. It's happening when all component action and nested components actions are done.

Check your code with console log on another place click to check

As you can see I placed a console log on every Home component rerender. You can check that all works fine.

P.S. I did some improvements to your code. Check if u like it. And add a comment to updateForm function. Check this one too, please.

Upvotes: 1

Tosin Felixson-Yusuf
Tosin Felixson-Yusuf

Reputation: 11

You evidently are not setting your state properly, here

   setDataForm({
      ...dataForm,
      [e.target.name]: e.target.value
    });

should be

 setDataForm(c => ({
     ...c,
     [e.target.name]: e.target.value
 }));

Upvotes: 0

Related Questions