0

I have this code as below in a custom module

define([
 'rjsResolver',
 'Magento_Customer/js/customer-data',
 'jquery'
], function (resolver, customerData, $) {
 'use strict';
 return function (checkoutLoader) {
 var mixin = {
 gtmEventTrigger: function() {
 console.log("Init Checkout Loader");
 console.log(customerData);
 // console.log(customerData.get('cart'));
 // console.log(customerData.get('cart')());
 $(cart_items).each(function(index,productData){
 product_detail = {};
 product_name = productData['product_name'];
 product_detail = {
 'item_name':product_name,
 }
 products.push(product_detail);
 })
 dataLayer.push({
 'event': 'begin_checkout',
 'ecommerce': {
 'currency': 'MYR',
 'value': grand_total, 
 'items': products
 }
 });
 }
 };
 mixin.gtmEventTrigger();
 return $.extend(checkoutLoader, mixin);
 };
});

I would like to know what is causing the customer cart data unable to be retrieved through the code console.log(customerData.get('cart')); , when I console.log I receive undefined value

Appreciate if someone can advise what is the correct way to write the codes to retrieve this customer cart data through a .js file

The location of the file is as follows

app/code/SR/ModifiedCheckout/view/frontend/web/js/checkout-loader.js

in which the checkout-loader.js is loaded like this

var config = {
 config: {
 mixins: {
 'Magento_Checkout/js/checkout-loader': {
 'SR_ModifiedCheckout/js/checkout-loader': true
 }
 }
 }
};

in the file path app/code/SR/ModifiedCheckout/view/frontend/requirejs-config.js

asked Mar 19, 2024 at 1:05
2
  • are you want information of current cart data? or Customer Data? Commented Mar 19, 2024 at 10:43
  • Hi, this issue has been solved ya, I put in the js code inside shipping.js file, app/design/frontend/MageBig/martfury/ecommerce/Magento_Checkout/web/js/view/shipping.js Commented Mar 20, 2024 at 2:06

2 Answers 2

1
  1. You was not able to retrieve the cart info in the checkout-loader mixin file, because the customer data was not actually loaded at that moment. So in this case something like this should work:

    customerData.get('cart').subscribe(function (cartData) {
     console.log(cartData);
    });
    
  2. The solution that you decided to use is also not perfect. Mainly because this will not work when you have only virtual products in cart. Because shipping.js will not be loaded in this case.

  3. Since you trying to push 'begin_checkout' event to GTM, I believe that you should follow a much easier approach. Just add your script right before body end. E.g.:

    view/frontend/layout/checkout_index_index.xml:

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
     <body>
     <referenceContainer name="before.body.end">
     <block name="gtm-begin-checkout" template="Vendor_Module::gtm_begin_checkout.phtml" />
     </referenceContainer>
     </body>
    </page>
    

    view/frontent/templates/gtm_begin_checkout.phtml:

    <script type="text/javascript">
     require([
     'Magento_Checkout/js/model/quote'
     ], function (quote) {
     let items = [];
     quote.getItems().forEach(function (cartItem) {
     items.push({
     item_name: cartItem.name,
     price: cartItem.price
     });
     });
     dataLayer.push({
     'event': 'begin_checkout',
     'ecommerce': {
     'currency': 'MYR',
     'value': quote.totals().subtotal,
     'items': items
     }
     });
     });
    </script>
    
answered Mar 20, 2024 at 18:44
2
  • Thank you for this, its easy to understand, have tried the fix you give and its working great! tysm Commented Mar 22, 2024 at 0:20
  • Hi @MagestyApps, I would like to ask, do you know how to retrieve info whether customer is logged in or not in a customer js script Commented Apr 26, 2024 at 2:08
0

For some reason in my code I need to put the source code in

app/design/frontend/MageBig/martfury/layout01/Magento_Checkout/web/js/view/shipping.js

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define([
 'jquery',
 'underscore',
 'Magento_Ui/js/form/form',
 'ko',
 'Magento_Customer/js/model/customer',
 'Magento_Customer/js/model/address-list',
 'Magento_Checkout/js/model/address-converter',
 'Magento_Checkout/js/model/quote',
 'Magento_Checkout/js/action/create-shipping-address',
 'Magento_Checkout/js/action/select-shipping-address',
 'Magento_Checkout/js/model/shipping-rates-validator',
 'Magento_Checkout/js/model/shipping-address/form-popup-state',
 'Magento_Checkout/js/model/shipping-service',
 'Magento_Checkout/js/action/select-shipping-method',
 'Magento_Checkout/js/model/shipping-rate-registry',
 'Magento_Checkout/js/action/set-shipping-information',
 'Magento_Checkout/js/model/step-navigator',
 'Magento_Ui/js/modal/modal',
 'Magento_Checkout/js/model/checkout-data-resolver',
 'Magento_Checkout/js/checkout-data',
 'uiRegistry',
 'mage/translate',
 'Magento_Checkout/js/model/shipping-rate-service',
 'Magento_Ui/js/model/messageList',
 'Magento_Customer/js/customer-data'
], function (
 ,ドル
 _,
 Component,
 ko,
 customer,
 addressList,
 addressConverter,
 quote,
 createShippingAddress,
 selectShippingAddress,
 shippingRatesValidator,
 formPopUpState,
 shippingService,
 selectShippingMethodAction,
 rateRegistry,
 setShippingInformationAction,
 stepNavigator,
 modal,
 checkoutDataResolver,
 checkoutData,
 registry,
 $t,
 $srs,
 messageList,
 customerData
) {
 'use strict';
 var popUp = null;
 return Component.extend({
 defaults: {
 template: 'Magento_Checkout/shipping',
 shippingFormTemplate: 'Magento_Checkout/shipping-address/form',
 shippingMethodListTemplate: 'Magento_Checkout/shipping-address/shipping-method-list',
 shippingMethodItemTemplate: 'Magento_Checkout/shipping-address/shipping-method-item'
 },
 visible: ko.observable(!quote.isVirtual()),
 errorValidationMessage: ko.observable(false),
 isCustomerLoggedIn: customer.isLoggedIn,
 isFormPopUpVisible: formPopUpState.isVisible,
 isFormInline: addressList().length === 0,
 isNewAddressAdded: ko.observable(false),
 saveInAddressBook: 1,
 quoteIsVirtual: quote.isVirtual(),
 /**
 * @return {exports}
 */
 initialize: function () {
 console.log("initialize shipping js");
 var product_name = 'n/a';
 var product_sku = 'n/a';
 var product_price = 'n/a';
 var product_brand = 'n/a';
 var product_category = 'n/a';
 var product_variant = 'n/a';
 var product_market_price = 'n/a';
 var product_wow_cashback = 'n/a';
 var product_shipping_wm = 'n/a';
 var product_shipping_em = 'n/a';
 var cart_items = customerData.get('cart')().items;
 var product_detail = {};
 var products = [];
 var product_price_total = 0.00;
 var grand_total = 0.00;
 $(cart_items).each(function(index,productData){
 product_detail = {};
 product_name = productData['product_name'];
 product_sku = productData['product_sku'];
 product_price = productData['product_price_value'];
 product_brand = productData['product_brand'];
 product_category = productData['product_category'];
 product_variant = productData['product_variant'];
 product_market_price = productData['product_market_price'];
 product_wow_cashback = productData['product_wow_cashback'];
 product_shipping_wm = productData['product_shipping_wm'];
 product_shipping_em = productData['product_shipping_em'];
 product_price_total = product_price * productData['qty'];
 grand_total = grand_total + product_price_total;
 product_detail = {
 'item_name':product_name,
 'item_id':product_sku,
 'price':product_price,
 'item_brand':product_brand,
 'item_category':product_category,
 'item_variant':product_variant,
 'quantity':productData['qty'],
 'salePrice':product_price,
 'marketPrice':product_market_price,
 'wowCashback':product_wow_cashback,
 'shipping_west_malaysia_hit':product_shipping_wm,
 'shipping_east_malaysia_hit':product_shipping_em,
 }
 products.push(product_detail);
 })
 dataLayer.push({
 'event': 'begin_checkout',
 'ecommerce': {
 'currency': 'MYR',
 'value': grand_total, 
 'items': products
 }
 });
 return this;
 },
 });
});

the cart in the customerData is readable through here

answered Mar 20, 2024 at 2:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.