Skip to content

Commit

Permalink
fix: race condition
Browse files Browse the repository at this point in the history
Fix race condition when render/clear is called in rapid succession. This issue was first spotted when trying to use this library in react:
Relevant issue : briosheje/react-html5-qrcode-reader#2
  • Loading branch information
itsUndefined committed Jan 30, 2023
1 parent 4a9a039 commit f22802e
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/html5-qrcode-scanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ export class Html5QrcodeScanner {
private persistedDataManager: PersistedDataManager;
private scanTypeSelector: ScanTypeSelector;
private logger: Logger;
private isClearing = false;

// Initally null fields.
private html5Qrcode: Html5Qrcode | undefined;
Expand Down Expand Up @@ -232,6 +233,7 @@ export class Html5QrcodeScanner {
public render(
qrCodeSuccessCallback: QrcodeSuccessCallback,
qrCodeErrorCallback: QrcodeErrorCallback | undefined) {
this.isClearing = false;
this.lastMatchFound = null;

// Add wrapper to success callback.
Expand Down Expand Up @@ -324,6 +326,8 @@ export class Html5QrcodeScanner {
* fails otherwise.
*/
public clear(): Promise<void> {
this.isClearing = true;

const emptyHtmlContainer = () => {
const mainContainer = document.getElementById(this.elementId);
if (mainContainer) {
Expand Down Expand Up @@ -546,6 +550,9 @@ export class Html5QrcodeScanner {
}

Html5Qrcode.getCameras().then((cameras) => {
if ($this.isClearing) {
return;
}
// By this point the user has granted camera permissions.
$this.persistedDataManager.setHasPermission(
/* hasPermission */ true);
Expand Down Expand Up @@ -612,6 +619,9 @@ export class Html5QrcodeScanner {
&& this.persistedDataManager.hasCameraPermissions()) {
CameraPermissions.hasPermissions().then(
(hasPermissions: boolean) => {
if ($this.isClearing) {
return;
}
if (hasPermissions) {
$this.createCameraListUi(
scpCameraScanRegion, requestPermissionContainer);
Expand Down Expand Up @@ -964,6 +974,9 @@ export class Html5QrcodeScanner {
CameraPermissions.hasPermissions().then(
(hasPermissions: boolean) => {
if (hasPermissions) {
if ($this.isClearing) {
return;
}
// Start feed.
// Assuming at this point the permission button exists.
let permissionButton = document.getElementById(
Expand Down

0 comments on commit f22802e

Please sign in to comment.