Home > front end >  Unable to call hooks in a class - react
Unable to call hooks in a class - react

Time:11-20

I'm trying to add speech recognition and a transcript of what they spoke to my website, where a user presses a button to start the mic, speaks into their mic, and the transcript of what they said is recorded and displayed on the screen.

I'm doing all this in a class component called App and here is my function to handle the speech recognition part:

Dictaphone = () => {
    const {
      transcript,
      listening,
      resetTranscript,
      browserSupportsSpeechRecognition
    } = useSpeechRecognition();
  
    if (!browserSupportsSpeechRecognition) {
      return <span>Browser doesn't support speech recognition.</span>;
    }
  };

In my render() part, this is what I'm returning related to the speech recognition part of my website:

<p>Microphone: {this.Dictaphone.listening ? 'on' : 'off'}</p>
<button onClick={this.Dictaphone.SpeechRecognition.startListening}>Start</button>
<button onClick={this.Dictaphone.SpeechRecognition.stopListening}>Stop</button>
<button onClick={this.Dictaphone.resetTranscript}>Reset</button>
<p>{this.Dictaphone.transcript}</p>

I'm getting this error:

Failed to compile.

src\App.js
  Line 15:9:  React Hook "useSpeechRecognition" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks

I'm not sure why I'm getting this error, but most importantly, I don't know how to actually implement what I'm trying to implement without using the useSpeechRecognition() hook. Could I have some help in regards to going around this?

CodePudding user response:

The error is straightforward hooks are allowed only inside function components. and since the Dictaphone function is not a component (it doesn't return React elements) it's considered as you're calling the hook inside the parent element which is a class component.

if you want Dictaphone to be a component just add return null at the end.

Dictaphone = () => {
    const {
       transcript,
       listening,
       resetTranscript,
       browserSupportsSpeechRecognition
    } = useSpeechRecognition();

    if (!browserSupportsSpeechRecognition) {
        return <span>Browser doesn't support speech recognition.</span>;
    }
    return null;
};

and create it at its own file Dictaphone.jsx.

  • Related