Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix onLoad race condition #100

Merged
merged 3 commits into from
Nov 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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