In Magento 2, js mixin is a wonderful concept to override/extend core js files. If we want to perform any action before executing any js script function or if want to extend a function or to modify any data without overwriting js, so mixin will be the best option for you.
In the following example, we are extending “Magento_Checkout/js/action/set-shipping-information” js file with our custom js “Company_Module/js/action/set-shipping-information-mixin” mixin file. To do that we need to create requirejs-config.js with following code given under directory path as app/code/Magemeta/Module/view/frontend:
var config = {
config: {
mixins: {
'Magento_Checkout/js/action/set-shipping-information': {
'Magemeta_Module/js/action/set-shipping-information-mixin': true
}
}
}
};
Next, we need to create set-shipping-information-mixin.js file under app/code/Magemeta/Module/view/frontend/web/js/action to extend original function. Here we are just appending some test data to shipping address in the following example of code snippet given:
/*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();
if (shippingAddress['extension_attributes'] === undefined) {
shippingAddress['extension_attributes'] = {'customField':"testvalue"};
}
// you can write here your code according to your requirement
return originalAction(); // it is returning the flow to original action
});
};
});
Hope this will help you guys!!