5
votes

I'm using the shopify-buy SDK to try and fetch the articles off of my Shopify store just using JavaScript on the frontend, following the "Expanding the SDK" directions here: https://shopify.github.io/js-buy-sdk/#expanding-the-sdk.

Using the code below, I am able to retrieve my articles and some of the fields that I need.

// Build a custom query using the unoptimized version of the SDK
const articlesQuery = client.graphQLClient.query((root) => {
  root.addConnection('articles', {args: {first: 10}}, (article) => {
    article.add('title')
    article.add('handle')
    article.add('url')
    article.add('contentHtml')
  })
})

// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
  console.log('articles data')
  console.log(data)
})

However, I really need to pull the featured image for each article as well, and unfortunately, when I add the line article.add('image') in my articlesQuery, the resulting articles data logs null. I tried building a custom productsQuery, and that has a similiar problem - I can retrieve some of the product fields, but when I try add the line product.add('images'), I just get null back from the storefront API.

Does anyone have experience building custom/expanded queries and successfully retrieving images?

2
can you add the output of console.log(data) ?Taki
did you try img? if returning null, either articles don't have image or property name you're trying to access does not exist. You found anywhere correct keyword to retrieve images or was adding image to your article was your idea?RegarBoy

2 Answers

1
votes

Try following:

// Fetch all products in your shop
client.graphQLClient.fetchAll().then((acticles) => {
  console.log(acticles);
});

And then check in console what sort of available property names your articles have. If SDK allows you get any image data, there should be for sure anything like imageSrc || imageUrl || img......

1
votes

Thanks to Rebecca Friedman on the js-buy-sdk repo's github issues section for providing this working solution:

const articlesQuery = client.graphQLClient.query((root) => {
  root.addConnection('articles', {args: {first: 10}}, (article) => {
    article.add('title')
    article.add('handle')
    article.add('url')
    article.add('contentHtml')
    article.addField('image', {}, (image) => {
      image.add('id')
      image.add('originalSrc')
    })
  })
})

// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
  console.log('articles data')
  console.log(data) // works!
})

Because the image field is its own object, you have to add a callback function to specify the fields you need.