Mfa Xyz
Mfa Xyz

Reputation: 35

Call a function from inside of another function in React Native

I want to call snapShotTaker function from inside of HelloWorldApp function but i get ERROR TypeError: undefined is not a function, js engine: hermes in terminal. How to solve this problem?

notifee.registerForegroundService(notification => {
  return new Promise(() => {
    // Long running task...
    setInterval(() => {
      HelloWorldApp.snapShotTaker();
    }, 2000);
  });
});

const HelloWorldApp = () => {
  const isAppForeground = useIsForeground();
  console.log('In Foreground?: ', isAppForeground);

  const cameraRef = useRef(null);
  const [finalPath, setPhotoPath] = useState('');

  const devices = useCameraDevices();
  const device = devices.front;

  if (device == null) {
    return <ActivityIndicator style={styles.indicator} size="large" />;
  }

  const snapShotTaker = async () => {
    const snapshot = await cameraRef.current.takeSnapshot({
      quality: 20,
      skipMetadata: true,
    });
    setPhotoPath('file://' + snapshot.path);
  };

Upvotes: 2

Views: 229

Answers (1)

Ugur Eren
Ugur Eren

Reputation: 2214

You simply can't call it outside of the component. However you can move the notifee code to inside of your component using the useEffect hook and call it there.

const HelloWorldApp = () => {
  const isAppForeground = useIsForeground();
  console.log('In Foreground?: ', isAppForeground);

  const cameraRef = useRef(null);
  const [finalPath, setPhotoPath] = useState('');

  const devices = useCameraDevices();
  const device = devices.front;

  if (device == null) {
    return <ActivityIndicator style={styles.indicator} size="large" />;
  }

  const snapShotTaker = async () => {
    const snapshot = await cameraRef.current.takeSnapshot({
      quality: 20,
      skipMetadata: true,
    });
    setPhotoPath('file://' + snapshot.path);
  };

  useEffect(() => {
    // Register your service
    notifee.registerForegroundService(notification => {
      return new Promise(() => {
        // Long running task...
        setInterval(() => {
         snapShotTaker();
        }, 2000);
      });
    });

    // You need to stop the service on cleanup, so it doesn't register multiple times.
    // See https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup
    return () => {
      notifee.stopForegroundService();
    };
  
  // You can pass the snapShotTaker function to the deps array but it won't affect it since it isn't memoized. See useCallback hook if you want to memoize it.
  });

Upvotes: 3

Related Questions