Reputation: 627
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
I'm getting this error when I tried using Camera API provided by Expo CLI to take picture. What my actual issue is that, it runs on my android device without any error, But whenever I run the app on browser i.e., react DOM, it produces this error in console.
Here is the code which I have copied from expo doc,
import { Camera } from "expo-camera";
import { useEffect, useState } from "react";
const TakeImage = () => {
const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
useEffect(() => {
(async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
setHasPermission(status === "granted");
})();
}, []);
if (hasPermission === null) {
return <View />;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.container}>
<Camera style={styles.camera} type={type}>
<View style={styles.buttonContainer}>
<TouchableOpacity
style={styles.button}
onPress={() => {
setType(
type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back
);
}}
>
<Text style={styles.text}> Flip </Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
};
Upvotes: 2
Views: 1545
Reputation: 159
You can't use a hook inside another hook because it breaks the rule Call Hooks from React function components and the function you pass to useEffect is a regular javascript function. What you can do is call a hook inside another custom hook shown below:
Your code:
useEffect(() => {
(async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
setHasPermission(status === "granted");
})();
}, []);
Change To:
useEffect(() => {
checkPermissions();
}, []);
const checkPermissions = async () => {
const {status} = await Camera.requestCameraPermissionsAsync();
setHasPermission(status === 'granted');
};
Upvotes: 3