// app/routes/test-add-sample-product.jsx import { json } from "@remix-run/node"; import { useLoaderData, useActionData, Form } from "@remix-run/react"; import { Page, Layout, Card, Banner, Button, InlineError, } from "@shopify/polaris"; import { authenticate } from "../shopify.server"; export const loader = async ({ request }) => { const { admin } = await authenticate.admin(request); // Fetch the first manual collection in the store const resp = await admin.graphql(` { collections(first: 1, query: "collection_type:manual") { nodes { id title } } } `); const result = await resp.json(); const collection = result.data.collections.nodes[0] || null; return json({ collection }); }; export const action = async ({ request }) => { const formData = await request.formData(); const collectionId = formData.get("collectionId"); const { admin } = await authenticate.admin(request); // 1️⃣ Create a dummy product const createRes = await admin.graphql( `#graphql mutation CreateDummyProduct($product: ProductCreateInput!) { productCreate(product: $product) { product { id title } userErrors { field message } } } `, { variables: { product: { title: "Dummy Test Product", descriptionHtml: "
This is a dummy product for testing.
", }, }, } ); const createJson = await createRes.json(); const createErrors = createJson.data.productCreate.userErrors; if (createErrors.length) { return json( { errors: createErrors.map((e) => e.message) }, { status: 400 } ); } const newProduct = createJson.data.productCreate.product; // 2️⃣ Add the new product to the selected collection const addRes = await admin.graphql( `#graphql mutation AddToCollection($id: ID!, $productIds: [ID!]!) { collectionAddProducts(id: $id, productIds: $productIds) { collection { id title } userErrors { field message } } } `, { variables: { id: collectionId, productIds: [newProduct.id], }, } ); const addJson = await addRes.json(); const addErrors = addJson.data.collectionAddProducts.userErrors; if (addErrors.length) { return json( { errors: addErrors.map((e) => e.message) }, { status: 400 } ); } const updatedCollection = addJson.data.collectionAddProducts.collection; return json({ success: true, product: newProduct, collection: updatedCollection, }); }; export default function TestAddSampleProduct() { const { collection } = useLoaderData(); const actionData = useActionData(); return (Please create at least one manual (non-smart) collection in your store first.
Product “{actionData.product.title}” ( {actionData.product.id}) was created and added to “ {actionData.collection.title}” ( {actionData.collection.id}).