Reputation: 103
So the problem is when the input value is auto-filled and when I click submit button input field value is not recognized unless I change something in there for example delete and add again the last word to the first name. How can I make value recognized immediately?
// This is 'context' from where we get info about 'user' like first name, last
// name, email etc
const { user } = useContext(UserContext);
const [firstName, changeFirstName] = useState(user.firstName);
const [lastName, changeLastName] = useState(user.lastName);
/**
* @param {Object} e
*/
const handleChange = (e) => {
handleUserInputChange(e);
changeFirstName(e.firstName);
changeLastName(e.lastName);
}
<input
type="text"
value={firstName}
name="firstName"
onChange={(e) => handleChange(e)}
/>
Upvotes: 1
Views: 878
Reputation: 3079
There is something fishy with your onChange
handler:
const handleChange = (e) => {
handleUserInputChange(e);
changeFirstName(e.firstName);
changeLastName(e.lastName);
}
At this point, you don't have access to the e.firstName
and e.lastName
values. The e
object is just the event from the onChange
call (find an example in the React docs here).
For the first name, you could instead use something like this:
const handleChange = (e) => {
changeFirstName(e.target.value);
}
Upvotes: 2
Reputation: 6255
I would recommend refactoring a little bit to make it more understandable. Anyway, you are looking to (input)=""
to change the value as user types. You can't have property as a const (constant) if you play to overwrite it.
html
<input #firstName
type="text"
(value)="firstName"
name="firstName"
(input)="onFirstNameChange(firstName.value)"/>
<input #lastName
type="text"
(value)="lastName"
name="lastName"
(input)="onLastNameChange(lastName.value)"/>
ts
firstName: string;
lastName: string;
onFirstNameChange(event: any) {
this.firstName = event;
}
onLastNameChange(event: any) {
this.firstName = event;
}
Upvotes: 0