Why, when the user enters data into the form for the first time, 'users' remains an empty array, as it was, and only after the second time button is pressed, the data is written to 'setUser?
import Card from "../UI/Card";
import Button from "../UI/Button";
const UserForm = (props) => {
const [users, setUsers] = useState([]);
const [data, setData] = useState({ username: "", age: "" });
const submitHandler = (e) => {
e.preventDefault();
setUsers([...users, data]);
console.log("2", users);
props.getUsers(users);
};
return (
<Card className={classes.container}>
<div>Username</div>
<input
type="text"
onChange={(e) => {
setData({ ...data, username: e.target.value });
}}
></input>
<div>Age (Years)</div>
<input
type="number"
onChange={(e) => setData({ ...data, age: e.target.value })}
></input>
<Button onClick={submitHandler}>Add User</Button>
</Card>
);
};
export default UserForm;
....................
CodePudding user response:
React State update takes time. So you need a useEffect
hook with state as a argument in it. so whenever the state change, this hook triggers and perform your state related functions.
useEffect(() => {
console.log(users)
props.getUsers(users);
}, [users]);
CodePudding user response:
it does change but how react works ?
when you update the value of one react hook and if this value
is different from the previous one the component
re-render with the new value
of the hook.
in you code you are trying to :
console.log("2", users);
this is just before the component
re-render so the new value
is not available yet, but directly after submitHandler
the component will re-render with new value
of users
you can understand better if you try to console log()
from inside your jsx
return (
<Card className={classes.container}>
{console.log('this is a new render and this is my users value :',users)}
</Card>
);
learn more here about React component lifecycle