How to Update Multiple Cart Line Items with applyCartLinesChange in Checkout Ui Extension

rajankumartpss
Shopify Partner
4 0 0

Hello Guys, I hope you are doing well.

Assume that, I have a cart having 2 line items. I want to Update the quantity of these 2 line items with applyCartLinesChange. This hook showing strange behaviour to me.

 

Below Code is Working good:

 

 

        await applyCartLinesChange({
            id: lines.current[0].id,
            type: 'updateCartLine',
            quantity: 2
        }).then((response) => console.log('response: 0', response, lines.current[0].id));

        await applyCartLinesChange({
            id: lines.current[1].id,
            type: 'updateCartLine',
            quantity: 2
        }).then((response) => console.log('response: 0', response, lines.current[1].id));

 

 

Below is the response of above code : 

rajankumartpss_1-1691633339117.png

 

Below Code is not working : This code only update the last item in map array list and shows the error for the rest of items.

 

        Promise.all(lines.current.map(async (line) => {
            await applyCartLinesChange({
                id: line.id,
                type: 'updateCartLine',
                quantity: 3
            }).then((response) => console.log('response', response, line.id));
        })).then(() => {
            console.log('All Executes');
        });

 

 

Below is response of above code :

rajankumartpss_0-1691633281188.png


Please help me, how can I Update the cart line items dynamically. A little help would be greatly appreciated.

Thanks

Reply 1 (1)

RobFarmLink
Shopify Partner
33 2 23

I couldn't get Promise.all method to run multiple line item changes in parallel (https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop was helpful). I think Shopify prevents it to nudge you to look up cart line item ID before every single applyCartLineChange() because the ID may change after any update to any line item (see https://github.com/Shopify/ui-extensions/blob/03d69b5691d819657fd0da4295d74dca28d85254/packages/ui-e...).

 

You probably gotta do 'um sequentially like in your first example or use a for...of loop like:

 

async function handleUpdateCart() {
    for (const line of unavailableCartLines) {
      const result = await applyCartLinesChange({
        type: "updateCartLine",
        id: line.id,
        quantity: line.quantity - line.unmetDemandQty,
      });
    }
}