43 lines
1.1 KiB
TypeScript
43 lines
1.1 KiB
TypeScript
import type React from "react";
|
|
import { createContext, useCallback, useContext, useMemo, useRef } from "react";
|
|
|
|
import { cnServices } from "@/front/Components/cookie/constants";
|
|
import useCookieNotice from "@/hooks/use-cookie-notice";
|
|
|
|
interface 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);
|
|
|
|
const getToken = useCallback(() => {
|
|
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;
|
|
}
|