diff --git a/package.json b/package.json index dd4b12a..73bc663 100644 --- a/package.json +++ b/package.json @@ -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": [ diff --git a/src/index.js b/src/index.js index df653c4..e44146b 100644 --- a/src/index.js +++ b/src/index.js @@ -119,7 +119,7 @@ class HCaptcha extends React.Component { } } - renderCaptcha() { + renderCaptcha(onReady) { const { isApiReady } = this.state; if (!isApiReady) return; @@ -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() { @@ -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(); + }); }); } diff --git a/tests/hcaptcha.spec.js b/tests/hcaptcha.spec.js index c78d532..03b301c 100644 --- a/tests/hcaptcha.spec.js +++ b/tests/hcaptcha.spec.js @@ -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"; @@ -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( + , + ); + + instance.handleOnLoad(); + }); + + describe("Query parameter", () => { beforeEach(() => {