Bigbob556677
Bigbob556677

Reputation: 2158

React Loses "this" In Callback From Third Party Library

In React, I'm using the Quagga.js library to decode barcodes from the webcam.

Everything is working fine except in the "OnDetected" function that Quagga calls when a barcode is scanned. When coming from a callback, the React code loses access to the "this" of the React Component.

Below is the code and the issue comes into play in the onDetected(result) function when called as a callback from the Quagga.onDetected(this.onDetected);

If feel like this issue is more of a misunderstanding of React itself rather than the library having an issue. If this is the case, some general principles for working with Third Party Libraries would be greatly appreciated.

onDetected(result) {
    this.processBarcode(result["codeResult"]["code"]); //<- "this" refers to the callback, not the react component
}

processBarcode(barcode) {
    if (barcode.startsWith("US-")) {
        this.setState({user_barcode: barcode});
    } else {
        this.setState({shop_drawing_barcode: barcode});
    }
}

componentDidMount() {
    (new Promise((resolve, reject) => {
        Quagga.init({
            inputStream: {
                name: "Live",
                type: "LiveStream",
                target: document.querySelector('#scanner_window'),    // Or '#yourElement' (optional)
                constraints: {
                    width: 480,
                    height: 480,
                    facingMode: "environment" // or user
                }
            },
            numOfWorkers: 1,
            decoder: {
                readers: ["code_128_reader"]
            }, locate: true

        }, (err) => {
            Quagga.start();
            console.log("Initialization finished. Ready to start");
            resolve();
        })
    })).then(() => {
        //Set the callback
        Quagga.onDetected(this.onDetected);
    });
}

Upvotes: 0

Views: 172

Answers (1)

vishnu sandhireddy
vishnu sandhireddy

Reputation: 1176

The this.onDetected might be passing the function without binding to any this. You have to explicitly bind this.onDetected

Quagga.onDetected(this.onDetected.bind(this));

Upvotes: 3

Related Questions