I'm trying to get useState to work when a user clicks up or down arrows and for some reason the state is not been updated.
Even if I setTimeout to see if index gets updated still not. Totally confused here with this.
import React, { useEffect, useState } from 'react';
const Wrapper = ({ children }) => {
const [index, setIndex] = useState(-1);
useEffect(() => {
document.addEventListener('keydown', handler);
return () => {
document.removeEventListener('keydown', handler);
};
}, []);
const handler = (event) => {
if (event.key === 'ArrowDown') {
setIndex(index + 1);
console.log('index = ', index);
}
};
return (
<div>
{children}
</div>
);
};
export default Wrapper;