How retrieve metafield data with a post purchase extension

How retrieve metafield data with a post purchase extension

AntoineBil
Shopify Partner
2 0 0


Hello, i'm working on a Shopify application with a post purchase extension and I'd like to understand how I could recover my metafield data saved with the app installation. It seems that with a post purchase extension we don't have access to the useAppMetafield or useApi methods. The idea is that the user arrives on the application, can choose an offer to display, save it and then retrieve the data in the extension to display it. I'd like to do all this with a metafield but it's impossible to retrieve the data. I've also tried authenticating to graphQL with the extension's request token to make a classic query, but with this type of extension it doesn't seem to work. Do you have any ideas? thank you very much

Reply 1 (1)

_amal
Shopify Partner
6 1 2

I've created a sample code based on the Shopify documentation, but I haven't tested it yet. Could you please try the metafield API snippets in my code? If you encounter any issues, I apologize for the inconvenience.

import {
	render,
	Banner,
	useExtensionInput,
} from '@shopify/post-purchase-ui-extensions-react';
import { useEffect } from 'react';

render('Checkout::PostPurchase::Render', () => <App />);

export function App() {
	const { storage, calculateChangeset } = useExtensionInput();
	const metafields = storage.initialData.shop.metafields;

	useEffect(() => {
		async function setMetafield() {
			try {
				// Attempt to set a new metafield using the calculateChangeset API
				// (https://shopify.dev/docs/api/checkout-extensions/post-purchase/api#changeset)

				const result = await calculateChangeset({
					changes: [
						{
							key: 'resource_name',
							namespace: 'global',
							value: 'product',
							valueType: 'string',
							type: 'set_metafield', // Action to set the metafield
						},
					],
				});
				console.log('Metafield set successfully:', result);
			} catch (error) {
				console.error('Failed to set metafield:', error);
			}
		}
		setMetafield();
	}, [calculateChangeset]);

	return <Banner title="Sample code, not tested" />;
}