Metafields variant to update when selecting other variant

Hi,

I created a variant metafield that tell the portions of an item. It is showing in the product page, the problem is that it doesn’t change when choosing another variant except when I reload the page. :

Video of the problem

Here is the JS code I added, but it is still not working :

/**
* This callback is called whenever the variant changes and allows to update data about the active variant
*/

}, {
key: "_onVariantChanged",
value: function _onVariantChanged(previousVariant, newVariant) {
// 6th: Portions

this._updatePortions(newVariant, previousVariant); // 7th: store availability

Later on

/**
* Update the Portions
*/

}, {
key: "_updatePortions",
value: function _updatePortions(newVariant) {
if (!this.options['showPortions'] || !newVariant) {
return;
}

var productPortions = this.element.querySelector('.ProductMeta__Portions');

if (productPortions && newVariant['portions']) {
productPortions.innerText = newVariant['portions'];
}
}

Can somebody help me?

Thank you!

When you debug it, does newVariant actually have a property called “portions”?

If I’m not mistaken you need to use the Storefront API to access metafields.

The easiest way would be adding the metafield to the variant HTML (e.g. data-portion=“{{ variant.metafields.whatever.portions}}”) then accessing that with Javascript by using the dataset property (e.g. variant.dataset.portion)

Good points by Marco.

Obviously, variant data would not have .portions (or [‘portions’]) because it’s pulled from the output of {{ product | json }} which does not include metafields.

You’d need to provide this data from your liquid. One way to do it is like this
(you need to provide proper namespace and key for the metafield, I’ve used mydata for example)
(may also need to use v.metafields.mydata.portions.value depending on how your metafields are set up).


And then in your JS code use portions[newVariant.id] instead of newVariant[‘portions’]