Jamal Ahmed
Jamal Ahmed

Reputation: 627

Invalid hook call. Hooks can only be called inside of the body of a function component, Error only occurs in browser not on mobile

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:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

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

Answers (1)

DhavalR
DhavalR

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

Related Questions