From 46b0f094a846bf50feb23342e4a076e792501bc0 Mon Sep 17 00:00:00 2001 From: Ellie Croce Date: Tue, 19 Nov 2024 14:39:27 -0600 Subject: [PATCH 1/2] feat: update recipe to use hooks and latest code --- docs/recipes/ReactNativeVisionCamera.md | 306 +++++++++++------------- 1 file changed, 138 insertions(+), 168 deletions(-) diff --git a/docs/recipes/ReactNativeVisionCamera.md b/docs/recipes/ReactNativeVisionCamera.md index ef7dd352..8208c9a7 100644 --- a/docs/recipes/ReactNativeVisionCamera.md +++ b/docs/recipes/ReactNativeVisionCamera.md @@ -75,60 +75,49 @@ Since the simulators do not offer a good way of testing the camera for this reci Before we can get to using the camera on the device, we must get permission from the user to do so. Let's edit the Welcome screen in Ignite to reflect the current permission status and a way to prompt the user. ```tsx -import { observer } from "mobx-react-lite"; -import React, { FC } from "react"; -import { AppStackScreenProps } from "../navigators"; -import { Camera, CameraPermissionStatus } from "react-native-vision-camera"; -import { Linking, View, ViewStyle } from "react-native"; -import { Button, Screen, Text } from "app/components"; +import { observer } from "mobx-react-lite" +import { FC, useCallback, useEffect, useState } from "react" +import { AppStackScreenProps } from "../navigators" +import { useCameraPermission } from "react-native-vision-camera" +import { Linking, View, ViewStyle } from "react-native" +import { Button, Screen, Text } from "app/components" interface WelcomeScreenProps extends AppStackScreenProps<"Welcome"> {} -export const WelcomeScreen: FC = observer( - function WelcomeScreen(_props) { - const [cameraPermission, setCameraPermission] = - React.useState(); +export const WelcomeScreen: FC = observer(function WelcomeScreen(_props) { + const [cameraPermission, setCameraPermission] = useState() - React.useEffect(() => { - Camera.getCameraPermissionStatus().then(setCameraPermission); - }, []); + const { hasPermission, requestPermission } = useCameraPermission() - const promptForCameraPermissions = React.useCallback(async () => { - const permission = await Camera.requestCameraPermission(); - Camera.getCameraPermissionStatus().then(setCameraPermission); + useEffect(() => { + setCameraPermission(hasPermission) + }, []) - if (permission === "denied") await Linking.openSettings(); - }, [cameraPermission]); + const promptForCameraPermissions = useCallback(async () => { + if (hasPermission) return + const permission = await requestPermission() + setCameraPermission(permission) - if (cameraPermission == null) { - // still loading - return null; - } + if (!permission) await Linking.openSettings() + }, [hasPermission, requestPermission]) - return ( - - - - Camera Permission:{" "} - {cameraPermission === null ? "Loading..." : cameraPermission} - - {cameraPermission !== "granted" && ( -