Skip to main content

parseMetafieldValue

The parseMetafieldValue function parses a Metafield's value from a string into a sensible type corresponding to the Metafield's type.

Example code

import {
parseMetafieldValue,
Metafield,
flattenConnection,
useShopQuery,
Metafield,
gql,
} from '@shopify/hydrogen';

const QUERY = gql`
query product($handle: String!) {
product: productByHandle(handle: $handle) {
metafield(namespace: "my_namespace", key: "my_key") {
id
type
namespace
key
value
createdAt
updatedAt
description
reference @include(if: $includeReferenceMetafieldDetails) {
__typename
... on MediaImage {
id
mediaContentType
image {
id
url
altText
width
height
}
}
}
}
}
}
`;

export function Product({handle}) {
const {data} = useShopQuery({query: QUERY, variables: {handle}});

const metafieldValue = parseMetafieldValue(data.product.metafield)

return (
<div>
{metafieldValue}
</div>
);
}

Arguments

ArgumentRequired
A Metafield object.Yes

Return type

Depending on the type specified in the passed Metafield, the following type is returned:

Metafield typevalue type
datedate
date_timedate
booleanBoolean
number_integerint
number_decimalfloat
jsonAn object
weightAn object with value and unit keys
dimensionAn object with value and unit keys
volumeAn object with value and unit keys
ratingAn object with scale_min, scale_max, and value keys
colorstring
single_line_text_fieldstring
multi_line_text_fieldstring
product_referencestring
file_referencestring
page_referencestring
variant_referencestring
urlstring