Skip to content

Commit

Permalink
Fix onLoad race condition (#100)
Browse files Browse the repository at this point in the history
* Fix onLoad race condition

* remove unused npm package

* remove extra new lines
  • Loading branch information
brdlyptrs authored Nov 4, 2021
1 parent 02c6518 commit 4c19cb4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 9 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@hcaptcha/react-hcaptcha",
"version": "0.3.8",
"version": "0.3.9",
"types": "types/index.d.ts",
"main": "dist/index.js",
"files": [
Expand Down
17 changes: 10 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ class HCaptcha extends React.Component {
}
}

renderCaptcha() {
renderCaptcha(onReady) {
const { isApiReady } = this.state;
if (!isApiReady) return;

Expand All @@ -132,7 +132,9 @@ class HCaptcha extends React.Component {
"callback" : this.handleSubmit,
});

this.setState({ isRemoved: false, captchaId });
this.setState({ isRemoved: false, captchaId }, () => {
onReady && onReady();
});
}

resetCaptcha() {
Expand All @@ -156,12 +158,13 @@ class HCaptcha extends React.Component {

handleOnLoad () {
this.setState({ isApiReady: true }, () => {
// trigger onLoad if it exists
const { onLoad } = this.props;
if (onLoad) onLoad();

// render captcha
this.renderCaptcha();
// render captcha and wait for captcha id
this.renderCaptcha(() => {
// trigger onLoad if it exists
const { onLoad } = this.props;
if (onLoad) onLoad();
});
});
}

Expand Down
20 changes: 19 additions & 1 deletion tests/hcaptcha.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, { useRef } from "react";
import ReactDOM from "react-dom";
import ReactTestUtils, { act } from "react-dom/test-utils";
import {getMockedHcaptcha, MOCK_EKEY, MOCK_TOKEN, MOCK_WIDGET_ID} from "./hcaptcha.mock";
Expand Down Expand Up @@ -177,6 +177,24 @@ describe("hCaptcha", () => {
expect(node.getAttribute("id")).toBe(null);
});

it("should not set id if no id prop is passed", (done) => {

const onLoad = jest.fn(() => {
expect(instance.state.captchaId).toBe(MOCK_WIDGET_ID);
done();
});

instance = ReactTestUtils.renderIntoDocument(
<HCaptcha
sitekey={TEST_PROPS.sitekey}
onLoad={onLoad}
/>,
);

instance.handleOnLoad();
});


describe("Query parameter", () => {

beforeEach(() => {
Expand Down

0 comments on commit 4c19cb4

Please sign in to comment.