Add captcha in inquiries form
This commit is contained in:
+24
-2
@@ -4,7 +4,8 @@ import { sanitizeText } from "@/lib/sanitize";
|
||||
import { createFieldValidation } from "@/lib/validation";
|
||||
import api from "@/service/api";
|
||||
import { CmsContact } from "@/types/TCms";
|
||||
import { useMemo, useState } from "react";
|
||||
import HCaptcha from "@hcaptcha/react-hcaptcha";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "react-toastify";
|
||||
import InputGroup from "../_components/InputGroup";
|
||||
@@ -26,6 +27,8 @@ const InquiresForm = ({
|
||||
contactData,
|
||||
}: InquiresFormProps) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [hcaptchaToken, setHcaptchaToken] = useState<string | null>(null);
|
||||
const captchaRef = useRef<HCaptcha>(null);
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
@@ -61,13 +64,24 @@ const InquiresForm = ({
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
[]
|
||||
[],
|
||||
);
|
||||
|
||||
const fields = contactData?.fields || defaultFields;
|
||||
const formFieldNames = useMemo(() => fields.map((f) => f.name), [fields]);
|
||||
|
||||
const onCaptchaVerify = (token: string) => {
|
||||
setHcaptchaToken(token);
|
||||
};
|
||||
|
||||
const onCaptchaExpire = () => {
|
||||
setHcaptchaToken(null);
|
||||
};
|
||||
const onSubmit = async (data: TInquiresForm) => {
|
||||
if (!hcaptchaToken) {
|
||||
toast.error("Please complete the captcha verification");
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = (await api.post("inquiries", { ...data })).data;
|
||||
@@ -167,6 +181,14 @@ const InquiresForm = ({
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<div className={`${colSpanClass}`}>
|
||||
<HCaptcha
|
||||
sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY || ""}
|
||||
onVerify={onCaptchaVerify}
|
||||
onExpire={onCaptchaExpire}
|
||||
ref={captchaRef}
|
||||
/>
|
||||
</div>
|
||||
<div className={`${colSpanClass} flex justify-end`}>
|
||||
<button className="bg-(--primary) cursor-pointer w-fit text-white rounded-full py-4 px-6">
|
||||
{isLoading ? <Loading /> : submitText}
|
||||
|
||||
Reference in New Issue
Block a user