I am working on tracking user engagement with an ecommerce store. One of the features is adding a shopping list of items to your cart. This event has a datalayer instance which gets overwritten when the page reload and populates the basket. Before that happens I am saving the datalayer to session storage. Then on page load, for each item added to the basket I want to log an add to cart event within Google Analytics 4. I intend to do this via a custom gtag event, but when this runs it goes into an infinite loop.
Example code below
var newCartItems = JSON.parse(sessionStorage.getItem("cartContents"));
var keyLength = Object.keys(newCartItems).length -1;
var myCustomCartProducts = newCartItems[keyLength].ecommerce.add.products;
for(i = 0 ; i < myCustomCartProducts.length; i++) {
gtag(
"event", "add_to_cart_multi", {
"value": myCustomCartProducts[i].price * myCustomCartProducts[i].quantity,
"currency": "{{Ga4 dlv ecommerce.currencyCode}}",
"page_type": "{{CJS - Page Type}}",
"search_term": "{{1 Cookie - searchterm}}",
"search_term_previous": "{{Cookie - searchtermprevious}}",
"search_term_all_lc": "{{Cookie - searchterm - Lowercase}}",
"search_term_previous_all_lc": "{{Cookie - searchtermprevious - Lowercase}}",
"is_user_logged_in_out": "{{MK - DL - user.status}}",
"product_line_quantity": myCustomCartProducts[i].quantity,
"product_line_price": myCustomCartProducts[i].price,
items: [
{
"item_name": myCustomCartProducts[i].name ,
"item_id": myCustomCartProducts[i].id ,
"price": myCustomCartProducts[i].price,
"item_brand": myCustomCartProducts[i].brand,
"item_category": myCustomCartProducts[i].category ,
"quantity": myCustomCartProducts[i].quantity
}]
});
}
When I change gtag to console.log the for loop completes normally.I am struggling to work out what is extending the length of the array/breaking the loop.


