56 lines
1.3 KiB
TypeScript
56 lines
1.3 KiB
TypeScript
import useCookieNotice from "@/hooks/use-cookie-notice";
|
|
import InitRecaptcha from "@/hooks/use-recaptcha";
|
|
import React, {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useEffect,
|
|
useMemo,
|
|
useRef,
|
|
} from "react";
|
|
import { cnServices } from "../lib/constants";
|
|
|
|
type ContextType = {
|
|
enabled: boolean;
|
|
getToken: () => string;
|
|
formRef: React.RefObject<HTMLFormElement | null>;
|
|
};
|
|
|
|
const RecaptchaContext = createContext<ContextType | null>(null);
|
|
|
|
export function RecaptchaProvider({ children }: { children: React.ReactNode }) {
|
|
const formRef = useRef<HTMLFormElement>(null);
|
|
const { status } = useCookieNotice(cnServices.RECAPTCHA);
|
|
|
|
useEffect(() => {
|
|
if (status && formRef.current) {
|
|
InitRecaptcha([formRef.current]);
|
|
}
|
|
}, [status]);
|
|
|
|
const getToken = useCallback(() => {
|
|
// @ts-expect-error grecaptcha global
|
|
return window.grecaptcha?.getResponse() || "";
|
|
}, []);
|
|
|
|
const value = useMemo(
|
|
() => ({
|
|
enabled: status,
|
|
getToken,
|
|
formRef,
|
|
}),
|
|
[status, getToken],
|
|
);
|
|
|
|
return (
|
|
<RecaptchaContext.Provider value={value}>
|
|
{children}
|
|
</RecaptchaContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useRecaptcha() {
|
|
const ctx = useContext(RecaptchaContext);
|
|
if (!ctx) throw new Error("useRecaptcha must be used inside provider");
|
|
return ctx;
|
|
}
|