GʀᴜᴍᴘʏCᴀᴛ
GʀᴜᴍᴘʏCᴀᴛ

Reputation: 9018

Shopify Storefront API how to pass key to variant fragment?

Rusty on my Graphql I'm using Shopify's Storefront API version 2024-10 I have a query of:

export const getProductQuery = /* GraphQL */ `
  query getProduct($handle: String!) {
    product(handle: $handle) {
      ...product
    }
  }
  ${productFragment}
`

in my Fragment I have:

import imageFragment from './image'
import seoFragment from './seo'

const productFragment = /* GraphQL */ `
  fragment product on Product {
    id
    handle
    availableForSale
    title
    description
    publishedAt
    tags
    descriptionHtml
    variants(first: 250) {
      edges {
        node {
          id
          title
          availableForSale
          selectedOptions {
            name
            value
          }
          price {
            amount
            currencyCode
          }
          metafield {
            key
            namespace
            type
          }
        }
      }
    }
    featuredImage {
      ...image
    }
    images(first: 20) {
      edges {
        node {
          ...image
        }
      }
    }
    seo {
      ...seo
    }
    tags
    updatedAt
  }
  ${imageFragment}
  ${seoFragment}
`

export default productFragment

and per the documentation on metafield I'm required to pass the key identifier.

Research

How can I get the metafield on the variant level from Shopify's Storefront API when I'm not sure what the required key should be?

Upvotes: 0

Views: 66

Answers (1)

Zeindelf
Zeindelf

Reputation: 86

You'll need just to pass "key" and "namespace" values to metafield field.

On metafield definition in your admin, you will find both namespace and key values. It'll be defined by {namespace}.{key}. e.g.: on you query, if value are "foo.bar":

variants(first: 250) {
  edges {
    node {
      id
      title
      availableForSale
      selectedOptions {
        name
        value
      }
      price {
        amount
        currencyCode
      }
      metafield(namespace: "foo", key: "bar") {
        key
        namespace
        type
      }
      # you can rename the field if has more metafields to retrive, like
      myCustomField: metafield(namespace: "custom", key: "foo") {
        key
        namespace
        type
      }
    }
  }
}

Upvotes: 1

Related Questions