Decrementing Item quantity using GraphQL query

Decrementing Item quantity using GraphQL query

Ventolin
Shopify Partner
2 0 0

I'm currently building a NextJS site using the Storefront API and have managed to use 'cartLinesAdd' to increment my product quantity in my cart by one on each click of a plus icon (adding 1 to quantity). At the moment i'm failing to have my minus icon do the opposite (using -1 on quantity) and wondering if there is a specific approach I should be using?

          onClick={async () => {
            await updateCart(cartData.cart.id, [
              {
                merchandiseId: merchandise.id,
                quantity: 1,
              },
            ])
            await refreshCartData()
          }}
 

To add context my onClick will work when adding 1, but fails when using -1

Many thanks!

Replies 3 (3)

SBD_
Shopify Staff
1829 272 417

Hey @Ventolin 

 

Sounds like you might be using a library, or helper function on top of the Storefront API.

 

Under the hood it should call cartLinesUpdate, which accepts cart lines with a `quantity` property.

 

You'll need to calculate the new quantity on your side (by adding/removing one) and then send the new quantity to the cartLinesUpdate mutation.

Scott | Developer Advocate @ Shopify 

Ventolin
Shopify Partner
2 0 0

Hi there, thanks for your reply.

 

The graphql query im using (apologies....forgot to attach) is formed like this:

 

export async function updateCart(cartId, lines) {
const updateCartMutation = gql`
mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
cartLinesAdd(cartId: $cartId, lines: $lines) {
cart {
id
}
}
}
`
const variables = {
cartId,
lines,
}
try {
return await graphQLClient.request(updateCartMutation, variables)
} catch (error) {
throw new Error(error)
}
}
 
Can you see anything that i'm doing wrong here?
 
Thanks again!
SBD_
Shopify Staff
1829 272 417

Thanks! After it's added, to change the quantity, use the cartLinesUpdate mutation.

Scott | Developer Advocate @ Shopify