11import { flattenStyles } from "@mendix/piw-native-utils-internal" ;
22import { ValueStatus } from "mendix" ;
3- import { createElement , ReactElement , useMemo } from "react" ;
3+ import { createElement , ReactElement , useCallback , useMemo , useRef } from "react" ;
44import { View } from "react-native" ;
55import { Camera , useCodeScanner , Code , useCameraDevice } from "react-native-vision-camera" ;
66import BarcodeMask from "react-native-barcode-mask" ;
@@ -16,21 +16,36 @@ export function BarcodeScanner(props: Props): ReactElement {
1616
1717 const styles = useMemo ( ( ) => flattenStyles ( defaultBarcodeScannerStyle , props . style ) , [ props . style ] ) ;
1818
19- const onCodeScanned = ( codes : Code [ ] ) => {
20- if ( props . barcode . status !== ValueStatus . Available || codes . length === 0 || ! codes [ 0 ] . value ) {
21- return ;
22- }
23- const { value } = codes [ 0 ] ;
19+ // Ref to track last scan time
20+ const lastScanRef = useRef ( 0 ) ;
2421
25- if ( value !== props . barcode . value ) {
26- props . barcode . setValue ( value ) ;
27- }
28- executeAction ( props . onDetect ) ;
29- } ;
22+ const onCodeScanned = useCallback (
23+ ( codes : Code [ ] ) => {
24+ const now = Date . now ( ) ;
25+
26+ // throttle: only allow once every 2000ms
27+ if ( now - lastScanRef . current < 2000 ) {
28+ return ;
29+ }
30+ lastScanRef . current = now ;
31+
32+ if ( props . barcode . status !== ValueStatus . Available || codes . length === 0 || ! codes [ 0 ] . value ) {
33+ return ;
34+ }
35+
36+ const { value } = codes [ 0 ] ;
37+ if ( value !== props . barcode . value ) {
38+ props . barcode . setValue ( value ) ;
39+ }
40+
41+ executeAction ( props . onDetect ) ;
42+ } ,
43+ [ props . barcode , props . onDetect ]
44+ ) ;
3045
3146 const codeScanner = useCodeScanner ( {
3247 codeTypes : [ "ean-13" , "qr" , "aztec" , "codabar" , "code-128" , "data-matrix" ] ,
33- onCodeScanned : throttle ( onCodeScanned , 2000 )
48+ onCodeScanned
3449 } ) ;
3550
3651 return (
@@ -58,16 +73,3 @@ export function BarcodeScanner(props: Props): ReactElement {
5873 </ View >
5974 ) ;
6075}
61-
62- export function throttle < F extends ( ...params : any [ ] ) => void > ( fn : F , threshold : number ) : F {
63- let wait = false ;
64- return function invokeFn ( this : any , ...args : any [ ] ) {
65- if ( ! wait ) {
66- fn ( ...args ) ;
67- wait = true ;
68- setTimeout ( ( ) => {
69- wait = false ;
70- } , threshold ) ;
71- }
72- } as F ;
73- }
0 commit comments