Issue
So, I'm facing a problem when I navigate to my scanner screen and go back the previous screen, then navigate again to my scanner screen, barcode scanner does not working. even console logs does not working. I have to clear cashe and all data from expo app in order to work scanner screen again. I really don't know what causing the porblem but highly suspicious about Navigation. Can anyone help me pls? Im adding my Scanner Screen right below.
import React, { useState, useEffect } from "react";
import {
Text,
View,
FlatList,
Button,
Modal,
Pressable,
Alert,
StyleSheet,
} from "react-native";
import { BarCodeScanner } from "expo-barcode-scanner";
import axios from "axios";
import { localIP, ngrokServer } from "../constants";
import allStyles from "../components/molecules/Styles";
const styles = allStyles;
export default function ScannerScreen({ navigation }) {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
useEffect(() => {
setReset(false);
});
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === "granted");
})();
}, []);
const handleBarCodeScanned = async ({ type, data }) => {
setScanned(true);
console.log("Data: ", data);
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.scannerScreenContainer}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
{scanned && reset && (
<Button title={"Tap to Scan Again"} onPress={() => setScanned(false)} />
)}
</View>
);
}
I'm using axios.post and thought maybe that was the cause of problem but when I removed that code block and run again it doesn't scan the QR code.
Solution
I had the same issue and I fixed it by adding a listener for focus events (emitted when the screen comes into focus).
This is what it looks like:
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// do something - for example: reset states, ask for camera permission
setScanned(false);
setHasPermission(false);
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === "granted");
})();
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);
Try using this code and see if it works.
Source: https://reactnavigation.org/docs/navigation-events/#navigationaddlistener
Answered By - Miztory
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.