react-zxing icon indicating copy to clipboard operation
react-zxing copied to clipboard

Torch is not working

Open stamahto opened this issue 2 years ago • 4 comments

I am encountering an issue with the torch.on() and torch.off() functions. When I call torch.on(), no noticeable changes occur, even console don't log any message.

I´m using the latest version 1.1.4

stamahto avatar Aug 15 '23 05:08 stamahto

What OS are you using?

adamalfredsson avatar Aug 15 '23 07:08 adamalfredsson

Android 13 I made my own custom torch function, which get user media by deviceId from my state and works fine.

    const handleToggleTorch = useCallback(() => {
        navigator.mediaDevices.getUserMedia({ video: { deviceId: deviceId } }).then(stream => {
            const track = stream.getVideoTracks()[0];
            track.applyConstraints({
                advanced: [{ torch: !isTorchOn } as any]
            });
            setIsTorchOn(!isTorchOn);
        });
    }, [deviceId, isTorchOn]);

As I look into your hook, did you consider put videoTrackRef into useCallback dependencies?

Btw. if you would update the code, please also update @zxing/library version

stamahto avatar Aug 16 '23 11:08 stamahto

That's strange! Unfortunately I'm in no possession of a torch-compatible device, so any help I could get with this would be highly appreciated!

@zxing/library has been updated now, in 2.0.0!

adamalfredsson avatar Aug 17 '23 13:08 adamalfredsson

I'm facing the same issue on Android 13. Sometimes the torch works, but only after toggling it multiple times. It's very unreliable for me.

I couldn't get @stamahto's handleToggleTorch function to work properly for me.

Edit:
I managed to fix the issue using a third-party package:

import { useTorchLight } from '@blackbox-vision/use-torch-light';

const streamRef = useRef<MediaStream | null>(null);
const [torchIsOn, toggleTorch] = useTorchLight(streamRef.current);

useEffect(() => {
  navigator.mediaDevices
    .getUserMedia({
      video: { facingMode: 'environment' },
    })
    .then((stream) => {
      streamRef.current = stream;
    });
}, [isScanning]);

Now I only use:

const {
  ref,
  torch: { isAvailable: torchAvailable },
} = useZxing({...});

to check if the torch is available.

For toggling and checking the torch state, I use:

const [torchIsOn, toggleTorch] = useTorchLight(streamRef.current);

This works reliably without issues.

Note: useTorchLight requires an older React version, but it works fine with React 19 too.

The root issue seems to be in the torch hook implementation of react-zxing. It would be great if someone could look into it and fix it, so third-party workarounds aren’t needed.

gerkim62 avatar Apr 17 '25 20:04 gerkim62