Riley-Brown / react-speech-to-text

React Hooks for Speech to Text
MIT License
118 stars 31 forks source link

Reset state of results #12

Closed marharyta closed 3 years ago

marharyta commented 3 years ago

Ideally, I would need to additions:

[] A way to clear the results array after the recording process is finished [] Away to trigger 'onResultsReady'

Riley-Brown commented 3 years ago

For clearing the results, I can add setResults to the hook return values then you could manually reset the results in a useEffect when isRecording === false

// in your component
useEffect(() => {
  if(!isRecording) {
    setResults([])
  }
}, [isRecording])

As for your second addition, I'm not sure what is meant by triggering onResultsReady, would this be when a new value is added to the results state array? Or the native browser event of a new speech result?

There is no programmatic way to trigger the native result event, this is only fired when the WebSpeechAPI returns a result from captured speech.

If you need to do something when the results state array is updated, you can use a useEffect in your code

useEffect(() => {
  if(results.length > 0) {
    const latestResult = results[results.length - 1]
    const { transcript } = latestResult
  }
}, [results])

If you need access to the native browser result, I can add a new callback prop of onResult that would be invoked on the WebSpeechAPI recognition.onresult event, and when the cross-browser google cloud speech result promise is resolved.

Important to note: The result event would differ depending on if the callback was invoked with WebSpeechAPI or using google cloud API, and you would have to handle parsing the transcript out of the different result events.

I would recommend to keep using the abstracted results state array to reduce complexity unless you really need the native result event

Riley-Brown commented 3 years ago

Just put out an update v0.8.0 with the setResults now returned in the hook so you can manually reset