Reputation: 99
I have the following react script, and I am trying to call the 'HandleListing' function as soon as the app opens. It then should detect what the user is saying, print it out on screen, and display the corresponding image. Below is my code:
import SpeechRecognition, {useSpeechRecognition} from "react-speech-recognition";
import map from "./map.jpeg";
import mapClosed from "./map-closed.jpeg";
import React from "react";
import { ImageBackground, StyleSheet } from "react-native";
let transcript;
function HandleListing() {
SpeechRecognition.startListening({
continuous: true,
});
transcript = useSpeechRecognition();
}
const App = () => (
HandleListing(),
(
<div>
{transcript && <div>{transcript}</div>}
{transcript == "hello" && (
<ImageBackground source={map}>
</ImageBackground>
)}
{transcript != "hello" && (
<ImageBackground
source={mapClosed}
></ImageBackground>
)}
</div>
)
);
export default App;
However I am getting the following error:
Hooks can only be called inside of the body of a function component
I am very new to react, so am unsure what I am doing wrong, could anyone assist please? thanks
Upvotes: 0
Views: 1872
Reputation: 114
As the error suggest react hook must only be initialize in react components (which is within the const APP =() => {}
), u should not wrap it in a function or outside the function components, same goes to every other hooks, useState(), useEffect() and etc.
const App = () => {
let transcript = useSpeechRecognition()
function Listening () {
SpeechRecognition.startListening({
continous : true
})
}
(
...
)
}
Upvotes: 1