import React, { useCallback, useState, useEffect } from "react";
// Custom hook from Cobalt for handling link operations.
// Run `npm i @cobalt-technology/react-link` to install the package.
import { useCobaltLink } from "@cobalt-technology/react-link";
export default function CobaltLinkDemo() {
const [linkToken, setLinkToken] = useState(null); // State to store the link token received from the Cobalt API
const [publicToken, setPublicToken] = useState(""); // State to store the public token received from the onSuccess callback
const [isReadyToInit, setIsReadyToInit] = useState(false); // State to determine if the component is ready to initialize the Cobalt link
// Callback function to handle success after receiving public token
const onSuccess = useCallback((public_token) => {
console.log("got the public_token: ", public_token);
setPublicToken("Public token: " + public_token);
// Exchange the public token for the access token
const accessTokenResponse = await fetch(`https://api.usecobalt.com/link/token/exchange?public_token=${public_token}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'client_id': '%COBALT_CLIENT_ID%',
'client_secret': '%COBALT_CLIENT_SECRET%'
},
});
const accessTokenData = await accessTokenResponse.json();
console.log('got the access_token: ', accessTokenData.token);
// Now you can save the access_token and use it to call the API
}, []);
// Destructuring the necessary methods and states from the useCobaltLink hook
const { init, loading } = useCobaltLink({
token: linkToken,
onSuccess,
});
// Effect to initialize the Cobalt link once conditions are met
useEffect(() => {
if (isReadyToInit && linkToken && !publicToken) {
init();
}
}, [isReadyToInit, linkToken, init]);
// Function to request a link token from the Cobalt API
const initLink = async () => {
try {
const response = await fetch(
"https://api.usecobalt.com/link/token/create", {
method: "POST",
headers: {
"Content-Type": "application/json",
client_id: "%COBALT_CLIENT_ID%",
client_secret: "%COBALT_CLIENT_SECRET%",
},
body: JSON.stringify({ user_id: "%REFERENCE_USER_ID%", org_id: "%REFERENCE_ORG_ID%" }),
}
);
const data = await response.json();
if (data && data.token) {
setLinkToken(data.token);
setIsReadyToInit(true);
} else {
console.error("Failed to obtain link token:", data.message);
}
} catch (err) {
console.error("Failed to setup integration:", err);
}
};
// Render a button that triggers the initLink function
return (
<div>
<button disabled={loading} onClick={initLink}>
Link Account
</button>
</div>
);
}