Back to Top

Use of Js Mixins in Magento 2

Updated 26 March 2024

Use of Js Mixins in Magento 2

Today I am going to explain how you can use js mixins in Magento 2 in this article. Suppose you have to do some task before any js script’s function run or to extend a function or to modify some data without overwrite of js so this blog will be very helpful for you.

At first you will need to create requirejs-config.js under app/code/Company/Module/view/frontend, like below:

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/action/set-shipping-information': {
                'Company_Module/js/action/set-shipping-information-mixin': true
            }
        } // this is how js mixin is defined
    }
};
// I am extending "Magento_Checkout/js/action/set-shipping-information" this js with our custom js "Company_Module/js/action/set-shipping-information-mixin".

Now, create set-shipping-information-mixin.js file under app/code/Company/Module/view/frontend/web/js/action to extend original function. So I am just appending some data to the shipping address only for example, here is the code :

/*jshint browser:true jquery:true*/
 /*global alert*/
 define([
     'jquery',
     'mage/utils/wrapper',
     'Magento_Checkout/js/model/quote'
 ], function ($, wrapper, quote) {
     'use strict';

     return function (setShippingInformationAction) {

         return wrapper.wrap(setShippingInformationAction, function (originalAction) {
            var shippingAddress = quote.shippingAddress();
            console.log(shippingAddress['middlename']);
            if (shippingAddress['middlename'] === null) {
                shippingAddress['middlename'] = "middlename";
            }
            console.log(shippingAddress);
            // you can write here your code according to your requirement
            return originalAction(); // it is returning the flow to original action
        });
     };
 });

Now if you console quote.shippingAddress() in js then the result will be as follows :

Searching for an experienced
Magento 2 Company ?
Find out More
Selection_016

I hope this blog will help you with custom functionality in your Magento 2 Development. You can also explore headless eCommerce development to develop high-quality interactive websites with the help of JavaScript frameworks.

Try this and if you have any queries then just comment below 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home