DEV Community

Rajiv (Ricky) Raghavan
Rajiv (Ricky) Raghavan

Posted on

TypeError: Cannot read property '89' of undefined-Hubspot

I am trying to get all the deals from Hubspot but for some reason I get errors for some deals.
The error is of the type Cannot read property '89' of undefined.

var fetch = require("node-fetch");
getHubspotData('https://api.hubapi.com/deals/v1/deal/paged?hapikey=demo&properties=dealname&properties=dealstage&properties=closedate&properties=dealtype&properties=type&properties=hubspot_owner_id&properties=amount&properties=notes_last_updated&includeAssociations=true');
async function getHubspotData(url) {
console.log("URL: " + url);
var iterations = 0;
for (let i = 0; i < 100; i++) {
await fetch(url)
.then((resp) => resp.json()) // Transform the data into json
.catch((error) => {
console.log("Error processing JSON: " + error)
}).then(function (data) {
console.log("Then-3");
iterations = iterations + 1;
console.log("I: " + iterations);
if ((data.hasMore == false) && (i == data.deals.length)) {
console.log("Synced all Deals From Hubspot");
console.log("Program Terminating...........................................");
process.exit();
}
if (data === undefined) {
console.log("data is undefined//////////////////////////////////////////////////////////////////////");
fetch(url)
.then((resp) => resp.json())
.then(function (data) {
console.log(data.deals.length);
}
)
} else {
console.log("data is NOT undefined");
}
var dealId = data.deals[i].dealId;
var dealName = data.deals[i].properties.dealname.value;
console.log(dealName);
offset = data.offset;
hasMore = data.hasMore;
dealLength = data.deals.length;
if ((hasMore == true) && (i + 1 >= dealLength)) {
console.log("NEW LOOP>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
var url = 'https://api.hubapi.com/deals/v1/deal/paged?hapikey=demo&properties=dealname&properties=dealstage&properties=closedate&properties=dealtype&properties=type&properties=hubspot_owner_id&properties=amount&properties=notes_last_updated&includeAssociations=true&offset=' + offset;
getHubspotData(url);
}
}).catch((error) => {
console.log("Error getting the deals //////////////////////////////////////////////////////////// " + error)
})
}

And it appears to be random. On one execution it might throw an error for deal 69-Cannot read property '69' of undefined and the next time I run it, it would throw errors on some other deals.
I tried to use an if condition to check whether the data is "undefined" but that doesn't help. Not sure why I am getting this error and cannot find a way to resolve this.
Any help on this matter would be greatly appreciated!

Top comments (0)