Display variant stock quantity in text element

I need to connect each variant stock quantity to a text element. If I had no variants, I could just connect it to the product stock quantity without problem. But as I have two sizes of the same product, I need to get the quantity info from the variants database, where the quantity field is a JSON object: {“trackQuantity”:true,“quantity”:7,“inStock”:true}.

Is there a way to extract each size quantity number and connect them to two text objects so that I can display them in my site? I really need this and I don’t know how to code, I can’t find any example.


Yes, there is, but it is a difficult task, as far as I know. I have an explanation in one question in here, I’ll try to find it.

Thank you! I’ll really apreciate that. I searched for answers but didn’t find none

I found the code that I used to check product options availability. Here it is:

see code below

Thank you very mucho Bruno! How do I connect the two size options inventory to the two text objects, now that I have the product options availability?

@eugeniagarat I’m so sorry, I really should have paid a better attention to the question. What you need is to track the quantity, I assumed it was only to know if you had the product in stock.

I don’t know if there is a way to track the quantity of a product or a variant by code, it does not seem like it, at least I could not find in the documentation.

Actually, I found a way, using the event, onInventoryVariantUpdated( ) .

You would need to create an event on the backend for that, and every time the inventory is updated, you can extract which variant was updated, and the quantity, and update a Tracked Variants Collection that you can query from the frontend. It would be really troublesome, but it can be done.

// events.js

import { updateTrackedVariant } from 'backend'

export async function wixStores_onInventoryVariantUpdated(event) {
  const { variants } = event
  const { id, newValue } = variants[0] // the first variant updated
  const { quantity } = newValue
  await updateTrackedVariant(id, quantity)

// backend

import wixData from 'wix-data'

export const updateTrackedVariant = async (variantId, quantity) => {
  await wixData.update('TrackedVariants', { variantId }, { quantity })

export const getTrackedVariants = async (id) => {
  return await wixData.query('TrackedVariants').eq('variantId', id).find()

// frontend

import { getTrackedVariants } from 'backend'

$w.onReady(async () => {
  const { items } = await getTrackedVariants('variantId')
  const { quantity } = items[0]

  $w('#textElement').text = String(quantity)

Thank you so muuuuuuuuuuuuuuuch! you are awesome! I’ll give it a try!