Hi, I’m working on the Drum Machine front end project and I’m having trouble getting events to work properly. Any time I press a key corresponding to a drum pad element or click on one of the drum pads, nothing happens and the state doesn’t seem to be updated. I’m using functional components instead of class components so I’m trying to use the useEffect()
hook for my key listener instead of component lifecycle methods.
I also seem to be having a problem with onClick events for some reason despite the fact I’ve been able to use them almost the same way before (in the Random Quote project).
Here’s an example of what I’m trying to do currently for the onClick event handler function
const handleClick = () => { dispatch(() => ({ type: 'DRUM_ACTIVATED', payload: drum.id })); playSound(drum.id); console.log('Played sound: ' + drum.id); }
which is then used in the onClick prop by the drum pad element
<div className="drum-pad" id={drum.id} onClick={handleClick}
here is the handler function I’m using for my key listener
const handleKeydown = event => { if(event.key === drum.key) { dispatch(() => ({ type: 'DRUM_ACTIVATED', payload: drum.id })); playSound(drum.id); console.log('Played sound: ' + drum.id); } }
as well as the hook I’m using for events
useEffect(() => { window.addEventListener('keydown', handleKeydown); return () => window.removeEventListener('keydown', handleKeydown); }, []);
and finally here is my codepen, I know it looks like vomit right now but I’m just trying to get something to work
I’m sure I’ve messed up something with the hooks for key events but I have no idea what I’m doing wrong with the onClick events since the only difference between how I’ve implemented it here and how I used it in the random quote project is that I have it inside of a wrapper function so that it also calls the playSound()
function