I have a form with some fields, which can be filled with speech recognition. I click on a button to play audio, then speech recognition starts listening.
The problem is for some reasons setBtnName('name')
doesn’t set the value and I get an error that __.mp3
doesn't exist
.
I believe my approach to call a function playName()
that sets
an argument and call another function
inside is incorrect.🤔 Maybe someone knows another way to set an argument and call a function with onClick()
directly?
const [btnName, setBtnName] = useState('')
function playName(){
setBtnName('name')
playSound()
}
function playAge(){
setBtnName('age')
playSound()
}
const audio = [`${btnName}.mp3`]
function playSound(){
//Play sound and start recognition
}
useState(){
//use {btnName} as a value for json file to compare it with transcript
}
return (
<div>
<p>Microphone: {listening ? 'on' : 'off'}</p>
<button
onClick={playName}
type="button"> Name
</button>
<button
onClick={playAge}
type="button"> Age
</button>
<div>{name}</div>
<div>{age}</div>
</div>
)
>Solution :
Do you use your buttonName or audio
inside playSound
? In this case, it’s not there yet. setBtnName will take effect in the next render.
You’d need either playSound('age')
/ playSound('name')
or useRef
or setTimeout
or combine useState
and useEffect
. So there are several ways.
Just one of the ways that seems more like what you want to achieve:
function playName(){
setBtnName('name')
playSound('name')
}
function playAge(){
setBtnName('age')
playSound('age')
}
function playSound(name){
const audio = [`${name}.mp3`]
//Play sound and start recognition
}