reactjswebkitspeechrecognition

Setting webkitspeechRecognition to state and changing language


So, I have set

let recognition = new SpeechRecognition;
recognition.continuous = true;
recognition.interimResults = false;
recognition.lang = 'en-US';

this.setState({
    recognition
});

console.log(this.state.recognition) gives me the speechrecognition object. because I shouldn't direct mutate the state with this.state.recognition.lang = 'ja-JP', I try to create a new object to set the recognition state to:

let newObject = {...this.state.recognition, lang: 'ja-JP'}

However, console.log(newObject) returns { lang: 'ja-JP' } and the rest of the properties are not cloned.

Is this a problem with the webkitspeechrecognition api and is there a workaround to getting it to work?


Solution

  • The object spread operator (...) returns the enumerable properties of an Object as key-value pairs. But not all types that inherit from the Object prototype have enumerable properties, and it looks like the native SpeechRecognition type is one of those--there are no iterable keys, just non-enumerable attributes. (So, ...(new SpeechRecognition) doesn't even throw an error; it has dutifully returned the zero enumerable properties of recognition. This is actually not all that surprising, there are lots of built-in Javascript object types that do not have enumerable properties.)

    I think you will need to create a new SpeechRecognition instance with the desired recognition.lang = 'ja-JP', and then setState to that. There is no spread or .assign() method that creates new SpeechRecognition instances from old ones, that I am aware of. I can see how this could create a situation in which there are multiple SpeechRecognition instances that the browser is allocating memory to; you might have to get creative and delete the reference to the old SpeechRecognition instance after setState is complete, so that garbage collection can do its work and leave you with just the one instance.