JamesBrill / react-speech-recognition

💬Speech recognition for your React app
https://webspeechrecognition.com/
MIT License
657 stars 119 forks source link

Prevent auto resetTranscript on listening when default value is set #65

Closed nirmaldymensions closed 3 years ago

nirmaldymensions commented 3 years ago

I've used this hook in a form where a textarea value gets updated with the spoken text. Works perfectly fine when the textarea is empty. However, if I have a default value set to the textarea, it gets reset on listening, which I'm guessing is the normal behaviour. But I don't want that. For eg. if I have "Default Notes Value" as the default value of the textarea and I start listening, the new content should append to the already present one and not replace it.

Here's a working example - https://codesandbox.io/s/adoring-wiles-q4tnf

I did try setting the default value state as the transcript onMount but it says transcipt is not a function:

useEffect(() => {
  notes && transcript(notes)
}, [])
JamesBrill commented 3 years ago

Hi @nirmaldymensions

The transcript string emitted by the Web Speech API cannot be modified directly, except by calling resetTranscript. If you want to display any additional text besides the transcript, you will need to manage that state yourself and concatenate the two. I've made some minor modifications to your example to demonstrate how you might do this: https://codesandbox.io/s/serene-feather-hl07f?file=/src/TextareaWithSpeech.js

Note that it was not the transcript that was being reset when you first started the Web Speech API, just your custom notes state. You were assigning the value of the transcript (initially an empty string) to your notes without storing the original notes value in its own state. As these are independent of each other, only the transcript would be displayed after the first update, and any default value that was there before would be wiped out. Hence the need to maintain your own state and combine the two in some way.

Hope that helps!