UNPKG

@swapper-finance/sdk

Version:
82 lines (70 loc) 2.29 kB
import { useEffect, useRef, useState, useCallback } from "react"; interface UseShift4SDKOptions { onOrderCompleted?: () => void; onOrderFailed?: () => void; // eslint-disable-next-line @typescript-eslint/no-explicit-any formConfiguration: any; // eslint-disable-next-line @typescript-eslint/no-explicit-any dependencies: any[]; } export const useShift4SDK = ({ onOrderCompleted, onOrderFailed, formConfiguration, dependencies, }: UseShift4SDKOptions) => { const [notLoadedInTime, setNotLoadedInTime] = useState(false); const containerRef = useRef<HTMLDivElement | null>(null); const initializeShift4SDK = useCallback(() => { if (!containerRef.current) { return; } containerRef.current.innerHTML = ""; ( window as unknown as Window & { Shift4CryptoSDK } )?.Shift4CryptoSDK?.createForm(formConfiguration) .on("ORDER_COMPLETED", async () => { if (onOrderCompleted) { onOrderCompleted(); } }) .on("ORDER_FAILED", async () => { if (onOrderFailed) { onOrderFailed(); } }) .append(containerRef.current); }, [formConfiguration, onOrderCompleted, onOrderFailed]); useEffect(() => { if (!containerRef.current || !formConfiguration) { return; } // Check if Shift4CryptoSDK is loaded // eslint-disable-next-line @typescript-eslint/no-explicit-any const shift4Sdk = (window as unknown as Window & { Shift4CryptoSDK: any }) .Shift4CryptoSDK; if (!shift4Sdk) { let counter = 0; const checkSDKLoaded = setInterval(() => { const isLoaded = // eslint-disable-next-line @typescript-eslint/no-explicit-any (window as unknown as Window & { Shift4CryptoSDK: any }) .Shift4CryptoSDK; if (isLoaded) { clearInterval(checkSDKLoaded); initializeShift4SDK(); } counter += 1; if (counter >= 30) { setNotLoadedInTime(true); clearInterval(checkSDKLoaded); } }, 100); return () => clearInterval(checkSDKLoaded); } else { initializeShift4SDK(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, dependencies); return { containerRef, notLoadedInTime }; };