Reputation: 3251
I am trying to read Shopify product page tags and ID's within Shopify's post-purchase script.
You don't need to be familiar with Shopify to understand this problem I am facing. It feels to be a Javascript problem and I'm having trouble understanding exactly how to reference these variables or objects.
Please read Shopify's docs here on the variables I can access.
My code
// Cart variables
var cartTagsString = "";
var cartProductIDString = "";
// Convert array of product tags into string
window.Shopify.order.lineitem.product.tags.forEach(function (item, index) {
cartTagsString = cartTagsString + item;
});
// Convert array of product id's into string
window.Shopify.order.lineitem.product.forEach(function (item, index) {
cartProductIDString = cartTagsString + item.id;
});
The error
“VM1370:44 Uncaught TypeError: Cannot read properties of undefined (reading 'product')”
Going to the exact line the error happens, it takes us here:
window.Shopify.order.lineitem.product.tags
Upvotes: 0
Views: 2280
Reputation: 218877
The documentation might actually be wrong in this case.
There is a table of properties which has something called lineItem
(which is different from lineitem
by the way, case matters). But the code samples show a property called lineItems
. And even in that table it describes lineItem
as "the line items for the order", which implies an array.
Going with the code samples, your forEach
would be something like this:
window.Shopify.order.lineItems.forEach(function (item, index) {
cartTagsString = cartTagsString + item.id;
});
Within that forEach
call, each item
is an element in that array. And item
should have a property called product
if you need to access that.
As for your first call to forEach
, I don't see anything on that page which has a tags
property. But the structure would be the same. For example, if any given item
has a tags
array, then you'd access that for the item
. For example:
window.Shopify.order.lineItems.forEach(function (item, index) {
cartTagsString = cartTagsString + item.id;
item.tags.forEach(function (tag) {
// do something with the tag
});
});
You might reach out to the vendor to ask them to clarify the documentation. But just as a debugging step, if all else fails you can always console.log
an object to observe what properties it has. Documentation is written by humans, and humans make mistakes. (Or perhaps written by someone who doesn't natively speak the language of the documentation and may mix up syntax from time to time.)
Upvotes: 1