I have next component:
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleUserKeyPress = useCallback((event) => {
if (event.keyCode === 13) {
doLogin({ username, password }, loginDispatch, callback);
}
}, []);
useEffect(() => {
window.addEventListener('keypress', handleUserKeyPress);
}, [handleUserKeyPress]);
<ProjectFormField
label={t('email')}
formInputProps={{
value: username,
onChange: (event) => setUsername(event.target.value),
}}
inputType="email"
/>
<ProjectFormField
label={t('password')}
formInputProps={{
value: password,
onChange: (event) => setPassword(event.target.value),
}}
type="passwordField"
/>
<Button
label={'loginEnter'}
id="login-button"
disabled={ !username || !password}
onClick={() => {
doLogin({ username, password });
}}
/>
***Where ProjectFormField is our custom app wrapper for Material ui text field component
When I do click on button the values of username and password exists in state. When I press the enter button, the callback function is working, but values in state are empty. I also tried solution with userRef, where the ref was the wrapper container of login component, but the result was the same. What I am doing wrong?
usernameandpassword) aren't updated withinhandleUserKeyPress, since it's a function using theuseCallbackhook. You could addusernameandpasswordto theuseCallbackdependency array, which would update the callback each time either of them changes. But I wouldn't recommend for performance reasons. - LuuuuduseCallback. Since it's a login form, memoization shouldn't improve performance too much. - Adrian Pascu