Ad

Shopify Buy SDK — Add Line Items Error

- 1 answer

I'm using the shopify buy SDK to create a custom storefront:

  • I get an error when trying to add a line item
  • The example code below all works, except when it hits the 'addLineItems' method: I've checked the parameters and they seem ok.

shopify.checkout.create().then((checkout) => {
  checkoutId = checkout.id
  console.log('checkout id: ' + checkoutId) // Works OK
})

shopify.product.fetchAll().then((products) => {
  lineItemsToAdd = [
    {variantId: products[0].variants[0].id, quantity: 1}
  ]
  console.log('line items to add: ' + lineItemsToAdd) // Works OK
})

shopify.checkout.addLineItems(checkoutId, lineItemsToAdd).then((checkout) => {
  console.log('checkout line items: ' + checkout.lineItems)
}) // Throws error

And the error I get is:

index.js?7327:3705 Uncaught (in promise) TypeError: Cannot read property 'checkoutLineItemsAdd' of undefined
at eval (index.js?7327:3705)
at <anonymous>

Ad

Answer

The issue is happening because Javascript is async by nature.

All of your calls executing at the same time and not in consequence. Because of that checkoutId, lineItemsToAdd variables are not set when addLineItems is executing.

You need to use promises to create a sequence. You can read about it here. Example of your code with a promise:

<script>

const client = ShopifyBuy.buildClient({
  domain: '-----------------------',
  storefrontAccessToken: '--------'
});
var checkoutPromise = client.checkout.create()
var productPromise = client.product.fetchAll()


Promise.all([checkoutPromise,productPromise]).then(([checkout,products]) => 
{
    var lineItemsToAdd = [
        {variantId: products[0].variants[0].id, quantity: 1}
      ]
    var checkoutId = checkout.id

    console.log('checkout id: ' + checkoutId)       
    console.log('line items to add: ' + lineItemsToAdd)

    client.checkout.addLineItems(checkoutId, lineItemsToAdd).then((checkout) => {
        console.log('checkout line items: ' + checkout.lineItems)
    })
})
</script>

P.S. Code above is not supported in IE

Ad
source: stackoverflow.com
Ad