I have component which provide double bind for input. So I want convey data to parent component with 2 ways: onBlur and on Enter button. Function which listens blur event works properly, but another function which have the same functionality do not see state data. I can't fix this bug for 2 hours!!
function NewFriend({ cancel = f => f, addNewFriend = f => f }) {
const [inputProps, resetValue] = useInput('');
useEffect(() => {
console.log(inputProps.value) // works correctly
}, [inputProps.value])
const blur = () => {
// it's works correctly
addNewFriend(inputProps.value)
resetValue('')
}
const keyDownHandlers = event => {
console.log(inputProps.value) // printing empty string
if (event.code === 'Enter') {
addNewFriend(inputProps.value)
resetValue('')
};
if (event.code === 'Escape') cancel();
}
useEffect(() => {
document.addEventListener('keydown', keyDownHandlers)
return () =>
document.removeEventListener('keydown', keyDownHandlers)
}, [])
return (
<div className='add-people'>
<input
type='text'
className='new-friend-input'
onBlur={blur}
autoFocus
{...inputProps} />
</div>
)
}
useInput hook:
export const useInput = initialValue => {
const [value, setValue] = useState(initialValue)
return [
{
value: value, onChange: event => setValue(event.target.value)
},
() => setValue(initialValue)
]}