Created
December 22, 2022 16:45
-
-
Save SeanMcGrath/fd1dae58fbe1b285d1831e6bc71c05c0 to your computer and use it in GitHub Desktop.
React hook for tilled.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
const scriptId = "tilled-js"; | |
/** | |
* Load and expose the tilled.js PCI-compliant payment capture utility. | |
* https://api.tilled.com/docs#section/Tilled.js | |
*/ | |
const useTilled = () => { | |
const [tilled, setTilled] = React.useState<any>(undefined); | |
const publishableKey = process.env.NEXT_PUBLIC_TILLED_PUB_KEY; | |
const account = process.env.NEXT_PUBLIC_BASE_TILLED_ACCT; | |
if (!publishableKey) { | |
throw new Error("no NEXT_PUBLIC_TILLED_PUB_KEY in env"); | |
} | |
if (!account) { | |
throw new Error("no NEXT_PUBLIC_BASE_TILLED_ACCT in env"); | |
} | |
React.useEffect(() => { | |
const existingScript = document.getElementById(scriptId); | |
if (!existingScript) { | |
const script = document.createElement("script"); | |
script.src = "https://js.tilled.com/v2"; | |
script.id = scriptId; | |
document.body.appendChild(script); | |
script.onload = () => { | |
if ((window as any).Tilled) { | |
setTilled( | |
new (window as any).Tilled( | |
publishableKey, | |
account, | |
window.location.origin === "https://app.golaunchpad.com" | |
? {} | |
: { sandbox: true } | |
) as any | |
); | |
} | |
}; | |
} | |
if (existingScript && !tilled && (window as any).Tilled) { | |
setTilled( | |
new (window as any).Tilled( | |
publishableKey, | |
account, | |
window.location.origin === "https://app.golaunchpad.com" | |
? {} | |
: { sandbox: true } | |
) as any | |
); | |
} | |
}); | |
return tilled; | |
}; | |
export default useTilled; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment