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.