For some reason the default value always shows up and the last value entered on the inputs does not.
APP.JS
import React, { useState } from 'react';
import User from './Components/User';
import Card from './Components/Card';
function App() {
const [user, setUser] = useState([{username: "Alex", age: 11}]);
const handleUserAdd = (user1) => {
setUser(prevState => ([
...prevState, user1
]));
console.log(user);
}
return (
<div className="App">
<Card>
<User onUserAdd={handleUserAdd}/>
</Card>
</div>
);
}
export default App;
USER.JS
import React, { useState } from 'react';
const User = (props) => {
const [name, setName] = useState("");
const [years, setYears] = useState(0);
const handleOnNameChange = (e) => {
setName(e.target.value);
}
const handleOnAgeChange = (e) => {
setYears(e.target.value);
}
const handleOnSubmit = (e) =>{
e.preventDefault();
//if(years !== 0){
const user = {
username: name,
age: years
};
props.onUserAdd(user);
//}
setName("");
setYears(0);
}
return (
<>
<form onSubmit={handleOnSubmit}>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">Username:</label>
<input className="form-control" aria-describedby="emailHelp" value={name} onChange={handleOnNameChange} />
</div>
<div className="mb-3">
<label htmlFor="exampleInputPassword1" className="form-label">Age:</label>
<input type="number" min={1} max={120} className="form-control" value={years} onChange={handleOnAgeChange} />
</div>
<button type="submit" className="btn btn-primary">Add User</button>
</form>
</>
);
}
export default User;
It shows Alex 11, which is the default value, if i put it on empty it will show it as an empty item. On the inputs, i entered 3 values: Value 1, 1; Value 2,2; Value 3,3. Value 3,3 is not showing up, if i eneter Value4,4 then Value 3 will show up and Value 4,4 will not. I do not understand why it's filling the first value with the default one instead of changing it to Value1,1. And why is it not showing the last one?
I would appreciate if you could help me.