0

I've created an input form that takes a value from users. After a button-click, the input field is cleaned. My implementation is as follows:

import React, { useState } from "react";

const initialValue = ["value 1", "value 2", "value 3"];

const Children = () => {
  const [enteredInputChildren, setEnteredInputChildren] = useState("");
  const [inputList, setInputList] = useState(initialValue);

  const AddValueChildrenHandler = (event) => {
    event.preventDefault();
    setInputList((prevList) => {
      return [...prevList, enteredInputChildren];
    });
    setEnteredInputChildren("");
    console.log(enteredInputChildren);
  };

  const InputChangeHandler = (event) => {
    setEnteredInputChildren(event.target.value);
  };

  return (
    <div className={classes.children_dev}>
      <h3>Children component</h3>
      <ul className={classes.list}>
        {inputList.map((item) => {
          return <li key={Math.random().toString()}>{item}</li>;
        })}
      </ul>
      <form onSubmit={AddValueChildrenHandler}>
        <input value={enteredInputChildren} onChange={InputChangeHandler} />
        <button type="submit">Add a value</button>
      </form>
    </div>
  );
};

As you can see above, the value of the variable enteredInputChildren is set to an empty string after setInputList(...). However, the output of the line console.log(enteredInputChildren) is not an empty string but the user input (what I expect is an empty string).

My question is why is the value of the variable enteredInputChildren getting updated after the button-click instead of during the function AddValueChildrenHandler call?

Thank you for your answer.

Nil
  • 1,209
  • 9
  • 20
Kai-Chun Lin
  • 185
  • 1
  • 2
  • 10
  • You're confused about how react `setState` works. This question is asked a few dozen times a week on Stackoverflow [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Andy Ray Jul 05 '23 at 22:09

0 Answers0