Skip to content

Instantly share code, notes, and snippets.

@andyxmas
Created July 24, 2023 08:27
Show Gist options
  • Save andyxmas/fb748f4a086c9ab6e7979761eaec37c1 to your computer and use it in GitHub Desktop.
Save andyxmas/fb748f4a086c9ab6e7979761eaec37c1 to your computer and use it in GitHub Desktop.
display customer metafields
import { getIDFromGID, camelToSpace } from "../../../helpers/helper.jsx";
import {
BlockLayout,
Text,
useAppMetafields,
useCustomer,
Heading,
InlineLayout,
useTranslate,
useExtensionApi
} from "@shopify/checkout-ui-extensions-react";
/**
* Renders key metafield data to show on the checkout page
*
*/
const DisplayGlobalMetafields = () => {
const { extension, extensionPoint } = useExtensionApi();
const customer = useCustomer();
const translate = useTranslate();
if (!customer && !extension.editor) {
return null;
}
console.log({extensionPoint})
// array of metafiels we wish to display
const metafieldKeys = ['accountManagerEmail', 'vesselName', 'vesselId']
const METAFIELD_NAMESPACE = "global";
const METAFIELD_TYPE = "customer";
const METAFIELD_ID = getIDFromGID(customer?.id);
const metafieldTitlesAndValues = metafieldKeys.map(key => {
if (extension.editor) {
// return placeholder values for the editor, as no customer is available
return {
title: translate(`global_metafields.${key}`),
value: 'metafield value will show here'
}
} else {
const metafieldArray = useAppMetafields({
id: METAFIELD_ID,
type: METAFIELD_TYPE,
namespace: METAFIELD_NAMESPACE,
key: key
})
if (metafieldArray[0]?.metafield?.value) {
return {
title: translate(`global_metafields.${key}`),
value: extension.editor ? 'metafield value will show here' : metafieldArray[0]?.metafield?.value
}
}
}
})
// filter out any null values
const validMetafieldTitlesAndValues = metafieldTitlesAndValues.filter(metafield => metafield)
console.log('validMetafieldTitlesAndValues', validMetafieldTitlesAndValues)
return (
<BlockLayout spacing={['extraTight', 'none']}>
<Heading>{translate("global_metafields.title")}</Heading>
{validMetafieldTitlesAndValues.map(({ title, value }) => (
<InlineLayout key={title}>
<Text emphasis="bold">{title}</Text>
<Text>{value}</Text>
</InlineLayout>
))}
</BlockLayout>
);
};
export { DisplayGlobalMetafields };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment