use state value change right after setState or state update
const buttonClick = (e) => {
console.log(e.target.innerText);
let pressedKey = e.target.innerText;
// let soundName;
sounds.forEach((item) => {
if (pressedKey === item.keyTrigger) {
setSoundFile(item.url);
// soundName = item.id;
}
});
};
// state updated on button click. use that update in a useEffect
// because setState is asynchronous. update will not yet take effect.
useEffect(() => {
if (soundFile) {
const audioElement = new Audio(soundFile);
audioElement.play();
}
}, [soundFile]);