import { useEffect, useRef, useState } from "react"
import Connect from "@mono.co/connect.js"
export function LinkAccountButton({ customerId }) {
const connectRef = useRef(null)
const [ready, setReady] = useState(false)
useEffect(() => {
const connect = new Connect({
key: import.meta.env.VITE_MONO_PUBLIC_KEY,
scope: "auth",
data: {
customer: { id: customerId }
},
onLoad: () => setReady(true),
onSuccess: async ({ code }) => {
const response = await fetch("/api/mono/exchange", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ code })
})
if (!response.ok) {
throw new Error("Could not complete Mono account linking")
}
},
onClose: () => console.log("Connect closed")
})
connect.setup()
connectRef.current = connect
return () => {
connect.close()
connectRef.current = null
}
}, [customerId])
return (
<button
type="button"
disabled={!ready}
onClick={() => connectRef.current?.open()}
>
{ready ? "Link a financial account" : "Loading account linking…"}
</button>
)
}