Reputation: 463
I am trying to integrate scanner-js
in my react app but I receive the error TypeError: Cannot read property 'scan' of undefined
.
You can find the code below:
import { scanner } from 'scanner-js';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
scan = () => {
scanner.scan(this.displayImagesOnPage, {
output_settings: [
{
type: 'return-base64',
format: 'jpg',
},
],
});
};
displayImagesOnPage(successful, mesg, response) {
if (!successful) {
// On error
console.error('Failed: ' + mesg);
return;
}
if (
successful &&
mesg != null &&
mesg.toLowerCase().indexOf('user cancel') >= 0
) {
// User cancelled.
console.info('User cancelled');
return;
}
var scannedImages = scanner.getScannedImages(response, true, false); // returns an array of ScannedImage
for (
var i = 0;
scannedImages instanceof Array && i < scannedImages.length;
i++
) {
var scannedImage = scannedImages[i];
var elementImg = scanner.createDomElementFromModel({
name: 'img',
attributes: {
class: 'scanned',
src: scannedImage.src,
},
});
}
}
render() {
return (
<div>
<button type="button" onClick={this.scan}>
Scan
</button>
</div>
);
}
}
export default Home;
When I hover over the scanner
object, the following things are showing, but I do not know why it's throwing an undefined error.
Can somebody help me to find the issue?
Thanks in advance.
Upvotes: 2
Views: 1810
Reputation: 23160
It's because you're importing it wrong. If you check the package on npm, you can see that there is no exported module, so you can't import a single export (import {scanner} from 'scanner-js'
) nor you can import the default export (import scanner from 'scanner-js
).
You need to import the entire module for side effects only, and it will add a global scanner
variable to the window
object.
import 'scanner-js';
console.log(typeof scanner);
// => object
console.log(typeof scanner.scan);
// => function
If you're using ESLint, you need to add scanner
as a global variable.
CodeSandbox link: https://codesandbox.io/s/scanner-js-hcz2j
Upvotes: 1