Skip to content

Commit ca6760d

Browse files
committed
feat: Show Alert when a code got scanned
1 parent 533bc6c commit ca6760d

File tree

1 file changed

+38
-7
lines changed

1 file changed

+38
-7
lines changed

package/example/src/CodeScannerPage.tsx

+38-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as React from 'react'
2-
import { useState } from 'react'
3-
import { StyleSheet, View } from 'react-native'
4-
import { useCameraDevice, useCodeScanner } from 'react-native-vision-camera'
2+
import { useCallback, useRef, useState } from 'react'
3+
import { Alert, AlertButton, Linking, StyleSheet, View } from 'react-native'
4+
import { Code, useCameraDevice, useCodeScanner } from 'react-native-vision-camera'
55
import { Camera } from 'react-native-vision-camera'
66
import { CONTENT_SPACING, CONTROL_BUTTON_SIZE, SAFE_AREA_PADDING } from './Constants'
77
import { useIsForeground } from './hooks/useIsForeground'
@@ -12,6 +12,26 @@ import type { Routes } from './Routes'
1212
import type { NativeStackScreenProps } from '@react-navigation/native-stack'
1313
import { useIsFocused } from '@react-navigation/core'
1414

15+
const showCodeAlert = (value: string, onDismissed: () => void): void => {
16+
const buttons: AlertButton[] = [
17+
{
18+
text: 'Close',
19+
style: 'cancel',
20+
onPress: onDismissed,
21+
},
22+
]
23+
if (value.startsWith('http')) {
24+
buttons.push({
25+
text: 'Open URL',
26+
onPress: () => {
27+
Linking.openURL(value)
28+
onDismissed()
29+
},
30+
})
31+
}
32+
Alert.alert('Scanned Code', value, buttons)
33+
}
34+
1535
type Props = NativeStackScreenProps<Routes, 'CodeScannerPage'>
1636
export function CodeScannerPage({ navigation }: Props): React.ReactElement {
1737
// 1. Use a simple default back camera
@@ -25,12 +45,23 @@ export function CodeScannerPage({ navigation }: Props): React.ReactElement {
2545
// 3. (Optional) enable a torch setting
2646
const [torch, setTorch] = useState(false)
2747

28-
// 4. Initialize the Code Scanner to scan QR codes and Barcodes
48+
// 4. On code scanned, we show an aler to the user
49+
const isShowingAlert = useRef(false)
50+
const onCodeScanned = useCallback((codes: Code[]) => {
51+
console.log(`Scanned ${codes.length} codes:`, codes)
52+
const value = codes[0]?.value
53+
if (value == null) return
54+
if (isShowingAlert.current) return
55+
showCodeAlert(value, () => {
56+
isShowingAlert.current = false
57+
})
58+
isShowingAlert.current = true
59+
}, [])
60+
61+
// 5. Initialize the Code Scanner to scan QR codes and Barcodes
2962
const codeScanner = useCodeScanner({
3063
codeTypes: ['qr', 'ean-13'],
31-
onCodeScanned: (codes, frame) => {
32-
console.log(codes, frame)
33-
},
64+
onCodeScanned: onCodeScanned,
3465
})
3566

3667
return (

0 commit comments

Comments
 (0)