I am making a drum machine that is supposed to activate audios when specific keys are pressed and then display the name of the sound. However, everytime the keys are pressed the if statements are not functioning properly because the useStates are not updating when the function / eventlistener is called. I am trying to use useEffect but I’m struggling and it is driving me insane.
To clarify: I am using a function component and not a class object component
useEffect(()=>{
document.addEventListener('keydown',handleKey)
}, [bank, power, volume])
function handleKey(e){
e.stopImmediatePropagation() // Stops the function from firing 2+ times
if (power){ // if the drum machine is on
if(bank === true) {const clip = audiosBank.find((clip) => clip.keyCode === e.which); // bank is boolean representing the second audio set
if (!clip) return; // clip eg: {keyCode: x, letter: x, name: x, src: x}
let csound = new Audio(clip.src)
csound.volume = volume // Volume is a useState connected to a input element with type range
csound.play()
setValue(prev => prev = clip.name) // Displays the audio name
}
}}
The problem is that power,bank,and volume are set to their default state, which is true, false, and 0.7 and they are not updating.
Can anyone please tell me the issue that I am not seeing.