So I'm building a drum-pad type of app, and almost everything is working, except this.
Edit: Put the whole thing on codesandbox, if anyone wants to have a look: codesandbox.io/s/sleepy-darwin-jc9b5?file=/src/App.js
const [index, setIndex] = useState(0);
const [text, setText] = useState("");
const [theSound] = useSound(drumBank[index].url)
function playThis(num) {
setIndex(num)
}
useEffect(()=>{
if (index !== null) {
setText(drumBank[index].id);
theSound(index);
console.log(index)
}
}, [index])
When I press a button, the index changes to the value associated with the button and then the useEffect hook plays the sound from an array at that index. However, when I press the same button more than once, it only plays once, because useState doesn't re-render the app when the index is changed to the same value.
I want to be able to press the same button multiple times and get the app to re-render, and therefore useEffect to run every time I press the button. Can anyone help me how to do this?
useEffect
hook at all for this and not just associate a keyPress event listener callback with a specific index value to pass totheSound
? Perhaps I'm missing some context in this minimal example? TheuseEffect
is intended to run an effect when a dependency changes, not when an asynchronous event happens. It doesn't seem to be the correct tool for the job. - Drew ReeseuseEffect
when it's not beneficial to you whatsoever. Just wrap all in one callbackplayThis
is enough. - vuongvuuseSound
in any callback, and for other than obvious hook reasons, buttheSound
can. I think a React ref may help you here. Do you have the ability to create a running codesandbox with this code mostly working? I have an idea but I am just not certain where thetext
state ordrumBank
come into play. - Drew Reese