Torch is not working
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
What OS are you using?
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
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!
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.