79641789

Date: 2025-05-28 08:26:05
Score: 0.5
Natty:
Report link

How about adding a 2-second restriction? This way, it would only allow assignment operations every 2 seconds.

import { useRef, useState } from "react"
import { TextInput } from "react-native"

interface UseBarcodeScanner {
    onScan: (barcode: string) => Promise<void> | void
}

const useBarcodeScanner = ({ onScan }: UseBarcodeScanner) => {
    const [barcode, setBarcode] = useState("")
    const inputRef = useRef<TextInput>(null)
    const lastScanTimeRef = useRef<number>(0)

    const handleStringListener = (text: string) => {
        const now = Date.now()
        if (now - lastScanTimeRef.current < 2000) {
            console.log("Barcode came so fast, it is ignored")
            return
        }

        setBarcode(text)
    }

    const handleEndEditing = () => {
        if (barcode.length > 0) {
            lastScanTimeRef.current = Date.now()
            void onScan(barcode)
            setBarcode("")
            inputRef.current?.focus()
        }
    }

    return {
        inputRef,
        barcode,
        inputProps: {
            value: barcode,
            onChangeText: handleStringListener,
            onEndEditing: handleEndEditing,
            onSubmitEditing: handleEndEditing,
            showSoftInputOnFocus: false,
            blurOnSubmit: false,
        },
    }
}

export default useBarcodeScanner
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): How
  • Low reputation (1):
Posted by: Live Stream