Am working on a camera feature in my mobile application, I am encountering a persistent issue with the permission request modal appearing repeatedly when navigating back to the Camera component. The modal is intended to request camera and storage permissions only once, upon the initial load of the component. However, every time I navigate away from and then back to the Camera screen, the permission request modal reappears, disrupting the user experience.
The following is my usePermissions hook,
interface UsePermissionsReturn {
requestCameraPermission: () => Promise<void>;
checkCameraPermission: (options: { displayPermissionRequestModals?: boolean; callback?: () => void }) => Promise<void>;
};
type NavigationParams = {
navigate(MODAL: string, arg1: { screen: string; params: { type: string; }; }): unknown;
screen: string,
params: PermissionScreenProps
}
export default function usePermissions(): UsePermissionsReturn {
const dispatch = useDispatch();
const navigation = useNavigation<NavigationParams>();
const cameraPermission = useSelector(({ UserSlice }) => UserSlice.cameraPermission);
const cameraLibraryPermission = useSelector(({ UserSlice }) => UserSlice.cameraLibraryPermission);
const requestCameraPermission = async () => {
const permissions = Platform.OS === "ios" ?
[PERMISSIONS.IOS.CAMERA, PERMISSIONS.IOS.MEDIA_LIBRARY] :
[PERMISSIONS.ANDROID.CAMERA, PERMISSIONS.ANDROID.ACCESS_MEDIA_LOCATION];
try {
const statuses = await requestMultiple(permissions);
dispatch(setBothCameraPermissions({
cameraPermission: statuses[permissions[0]],
cameraLibraryPermission: statuses[permissions[1]]
}));
console.log('Camera permissions set: ', cameraPermission, cameraLibraryPermission);
} catch (error) {
console.error("Error requesting camera permissions:", error);
}
};
const checkCameraPermission = async ({ displayPermissionRequestModals = false, callback }: { displayPermissionRequestModals?: boolean; callback?: () => void }) => {
if (cameraPermission === CAMERA_PERMISSION_NOT_SET && cameraLibraryPermission === CAMERA_LIBRARY_PERMISSION_NOT_SET) {
if (displayPermissionRequestModals) {
navigation.navigate(NAVIGATORS.MODAL, {
screen: MODAL_SCREENS.PERMISSIONS,
params: {
type: PERMISSION_TYPES.CAMERA_REQUEST
}
});
}
return;
}
const permissions = Platform.OS === "ios" ?
[PERMISSIONS.IOS.CAMERA, PERMISSIONS.IOS.MEDIA_LIBRARY] :
[PERMISSIONS.ANDROID.CAMERA, PERMISSIONS.ANDROID.ACCESS_MEDIA_LOCATION];
try {
const statuses = await checkMultiple(permissions);
dispatch(setBothCameraPermissions({
cameraPermission: statuses[permissions[0]],
cameraLibraryPermission: statuses[permissions[1]]
}));
if (displayPermissionRequestModals) {
switch (statuses[permissions[0]]) {
case RESULTS.DENIED:
navigation.navigate(NAVIGATORS.MODAL, {
screen: MODAL_SCREENS.PERMISSIONS,
params: { type: PERMISSION_TYPES.CAMERA_ERROR }
});
break;
}
}
if (displayPermissionRequestModals) {
switch (statuses[permissions[1]]) {
case RESULTS.DENIED:
navigation.navigate(NAVIGATORS.MODAL, {
screen: MODAL_SCREENS.PERMISSIONS,
params: {
type: Platform.OS === "android" ? PERMISSION_TYPES.CAMERA_ERROR : PERMISSION_TYPES.CAMERA_REQUEST
}
});
break;
case RESULTS.BLOCKED:
navigation.navigate(NAVIGATORS.MODAL, {
screen: MODAL_SCREENS.PERMISSIONS,
params: { type: PERMISSION_TYPES.CAMERA_ERROR }
});
break;
}
}
callback && callback();
} catch (error) {
console.error("Error checking camera permissions:", error);
}
};
return { requestCameraPermission, checkCameraPermission };
}
This is the camera component,
const flashModeService = new FlashModeService();
const cameraService = new CameraService();
const Camera = () => {
const navigation = useNavigation();
const [flashMode, setFlashMode] = useState(RNCamera.Constants.FlashMode.off);
const [cameraType, setCameraType] = useState(RNCamera.Constants.Type.back);
const { ref, callbackRef } = useCallbackRef();
const { seconds, recording, startRecordingVideo, stopRecordingVideo } = useCamera(ref);
const { checkCameraPermission } = usePermissions();
const [hasCameraPermission, setHasCameraPermission] = useState(false);
const [showSuccessMessage, setShowSuccessMessage] = useState(false);
useEffect(() => {
const handleCheckPermissionOnLoad = async () => {
await checkCameraPermission({
displayPermissionRequestModals: true,
callback: () => {
setHasCameraPermission(true);
setShowSuccessMessage(true);
setTimeout(() => {
setShowSuccessMessage(false);
}, 5000);
}
});
};
handleCheckPermissionOnLoad();
}, []);
const onTorchPress = () => {
setFlashMode(flashModeService.getNewFlashMode(flashMode));
};
const changeCameraType = () => {
setCameraType(cameraService.getNewCameraType(cameraType));
};
return (
<SafeAreaView style={styles.container}>
<RNCamera
ratio={"4:3"}
ref={callbackRef}
style={styles.camera}
type={cameraType}
flashMode={flashMode}
captureAudio={true}>
<View style={styles.header}>
<TouchableOpacity onPress={navigation.goBack}>
<Icon
name="close"
size={24}
color="#FFF"
style={styles.closeIcon}
/>
</TouchableOpacity>
{recording && (
<View style={styles.timer}>
<Text style={styles.timerText}>Time Remaining</Text>
<View style={styles.timeContainer}>
<View style={styles.dot} />
<Text style={styles.timerText}>00:{seconds}</Text>
</View>
</View>
)}
{cameraService.isBackCamera(cameraType) && (
<TouchableOpacity onPress={onTorchPress}>
<Icon
name="flash-on"
size={24}
color="#FFF"
style={styles.torchIcon}
/>
</TouchableOpacity>
)}
</View>
<View style={styles.captureContainer}>
<TouchableOpacity
onLongPress={startRecordingVideo}
onPressOut={stopRecordingVideo}
style={[
styles.captureButton,
recording ? styles.captureButtonInProgress : null
]}>
</TouchableOpacity>
<TouchableOpacity onPress={changeCameraType} disabled={recording}>
<Icon
name="flip-camera-ios"
size={54}
color="#FFF"
style={styles.switchCameraIcon}
/>
</TouchableOpacity>
</View>
<View style={styles.footer}>
<FlashNotification
visible={showSuccessMessage}
message="Permissions granted!"
/>
<Text style={styles.footerText}>Hold to record video</Text>
</View>
</RNCamera>
</SafeAreaView>
);
};
export default Camera;
This is the store,
import { createSlice } from "@reduxjs/toolkit";
import { CAMERA_LIBRARY_PERMISSION_NOT_SET, CAMERA_PERMISSION_NOT_SET } from "@utils/constants";
export const UserSlice = createSlice({
name: "UserSlice",
initialState: {
user: {},
cameraPermission: CAMERA_PERMISSION_NOT_SET,
cameraLibraryPermission: CAMERA_LIBRARY_PERMISSION_NOT_SET
},
reducers: {
setUser: (state, action) => {
state.user = action.payload;
},
setBothCameraPermissions: (state, action) => {
state.cameraPermission = action.payload.cameraPermission;
state.cameraLibraryPermission = action.payload.cameraLibraryPermission;
}
}
});
export const { setUser, setBothCameraPermissions } = UserSlice.actions;
export default UserSlice.reducer;
import AsyncStorage from "@react-native-async-storage/async-storage";
import {configureStore} from "@reduxjs/toolkit";
import {combineReducers} from "redux";
import {persistReducer} from "redux-persist";
import thunk from "redux-thunk";
import UserSlice from "./UserSlice";
const reducers = combineReducers({
UserSlice,
});
const persistConfig = {
key: "root",
storage: AsyncStorage,
whitelist: ["UserSlice"], // add reducers you want to persist here
};
const persistedReducer = persistReducer(persistConfig, reducers);
const store = configureStore({
reducer: persistedReducer,
middleware: [thunk],
});
export default store;
I need help ensuring that the permission request modal appears only when permissions are not granted. Any help will be greatly appreciated
The root cause of this issue seems to stem from the useEffect hook inside the Camera component, which is responsible for checking and requesting permissions on component mount. Despite attempts to optimize this behavior, such as leveraging local state to track permission status and using navigation hooks, the problem persists.