In a functional React component, I'm trying to do a fairly simple operation-
const TestClass = ({lastIndex}) => {
const [activeIndex, setActiveIndex] = useState(0);
const [fullScreenGallery, setFullScreenGallery] = useState(false);
const handleKeyChange = (e) => {
switch(e.code) {
case 'ArrowLeft':
if(activeIndex - 1 < 0) return setActiveIndex(lastIndex);
return setActiveIndex(activeIndex-1);
case 'ArrowRight':
if(activeIndex + 1 > lastIndex) return setActiveIndex(0);
return setActiveIndex(activeIndex+1);
case 'Escape':
if(fullScreenGallery) {
// closeFullScreenGallery();
return;
}
}
}
useEffect(() => {
document.addEventListener('keydown', handleKeyChange);
// other event listeners
}, []);
return (
<div>
// some code
</div>
)
}
Issue is, inside handleKeyChange, the value of activeSlide doesn't change after 1, even when I press the key. Can anyone point-out what I'm doing wrong? Same goes for fullScreenGallery.
If I try to add activeSlide and fullScreenGallery as dependencies in useEffect, my event listener starts getting adding whenever the dependency changes and I end up crashing my page.
This code was part of a class component and I'm trying to convert this class to a functional component. In the class component, useEffect code was written inside componentDidMount.