I’m building a HubSpot UI extension using React. I want the extension to fetch deal data automatically when the component loads. Here’s a simplified version of my code:
import React, {useState, useEffect} from "react";
import {Text, Flex, hubspot} from "@hubspot/ui-extensions";
// Register extension
hubspot.extend(({context}) => <Extension context={context}/>);
const Extension = ({context}) => {
const dealId = context?.crm?.objectId;
const [properties, setProperties] = useState(null);
const [contactIds, setContactIds] = useState([]);
const [companyIds, setCompanyIds] = useState([]);
useEffect(() => {
const fetchDealData = async () => {
try {
const response = await hubspot.fetch(`https://api.hubapi.com/crm/v3/objects/0-3/${dealId}?properties=num_associated_contacts,no_of_rooms&associations=contacts,companies`,
{
method: "GET",
});
const data = await response.json();
setProperties(data.properties);
const companies =
data.associations?.companies?.results.map((r) => r.id) || [];
const contacts =
data.associations?.contacts?.results.map((r) => r.id) || [];
setCompanyIds([...new Set(companies)]);
setContactIds(contacts);
} catch (error) {
console.error("Error fetching deal data:", error);
}
};
if (dealId) {
fetchDealData();
}
}, [dealId]); // Run once when dealId is available
return (
<Flex direction="column" gap="medium">
<Text>Deal Data (Loaded on Mount)</Text>
{properties ? (
<Flex direction="column" gap="small">
<Text>Created At: {properties.createdate}</Text>
<Text>Contacts: {contactIds.join(", ")}</Text>
<Text>Companies: {companyIds.join(", ")}</Text>
</Flex>
) : (
<Text>Loading...</Text>
)}
</Flex>
);
};
The link is added in the permittedUrls section
"permittedUrls": {
"fetch": [
"https://api.hubapi.com"
],
"iframe": [],
"img": []
},