Skip to content

Commit 4c19cb4

Browse files
authored
Fix onLoad race condition (#100)
* Fix onLoad race condition * remove unused npm package * remove extra new lines
1 parent 02c6518 commit 4c19cb4

3 files changed

Lines changed: 30 additions & 9 deletions

File tree

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@hcaptcha/react-hcaptcha",
3-
"version": "0.3.8",
3+
"version": "0.3.9",
44
"types": "types/index.d.ts",
55
"main": "dist/index.js",
66
"files": [

src/index.js

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ class HCaptcha extends React.Component {
119119
}
120120
}
121121

122-
renderCaptcha() {
122+
renderCaptcha(onReady) {
123123
const { isApiReady } = this.state;
124124
if (!isApiReady) return;
125125

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

135-
this.setState({ isRemoved: false, captchaId });
135+
this.setState({ isRemoved: false, captchaId }, () => {
136+
onReady && onReady();
137+
});
136138
}
137139

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

157159
handleOnLoad () {
158160
this.setState({ isApiReady: true }, () => {
159-
// trigger onLoad if it exists
160-
const { onLoad } = this.props;
161-
if (onLoad) onLoad();
162161

163-
// render captcha
164-
this.renderCaptcha();
162+
// render captcha and wait for captcha id
163+
this.renderCaptcha(() => {
164+
// trigger onLoad if it exists
165+
const { onLoad } = this.props;
166+
if (onLoad) onLoad();
167+
});
165168
});
166169
}
167170

tests/hcaptcha.spec.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from "react";
1+
import React, { useRef } from "react";
22
import ReactDOM from "react-dom";
33
import ReactTestUtils, { act } from "react-dom/test-utils";
44
import {getMockedHcaptcha, MOCK_EKEY, MOCK_TOKEN, MOCK_WIDGET_ID} from "./hcaptcha.mock";
@@ -177,6 +177,24 @@ describe("hCaptcha", () => {
177177
expect(node.getAttribute("id")).toBe(null);
178178
});
179179

180+
it("should not set id if no id prop is passed", (done) => {
181+
182+
const onLoad = jest.fn(() => {
183+
expect(instance.state.captchaId).toBe(MOCK_WIDGET_ID);
184+
done();
185+
});
186+
187+
instance = ReactTestUtils.renderIntoDocument(
188+
<HCaptcha
189+
sitekey={TEST_PROPS.sitekey}
190+
onLoad={onLoad}
191+
/>,
192+
);
193+
194+
instance.handleOnLoad();
195+
});
196+
197+
180198
describe("Query parameter", () => {
181199

182200
beforeEach(() => {

0 commit comments

Comments
 (0)