Remix

How to Create Products in a Shopify Remix App using GraphQL Mutations?

In this blog post, we will delve into the process of creating products within a Shopify Remix app using GraphQL mutations.

Remix is a powerful framework for building Shopify apps, and GraphQL Mutations offer a flexible way to create and manage data within your store. Leveraging the power of GraphQL, we can seamlessly integrate product creation functionality into our applications, providing users with a streamlined experience for adding new products to their Shopify stores.

Steps to Create Products in a Shopify Remix App using GraphQL Mutations:

Prerequisites:

Before proceeding, ensure that the user has the necessary permissions and write access scope to create products within the Shopify store.

Step 1: Set Up Authentication and GraphQL Mutation

First, we need to set up authentication to ensure that the user has the necessary permissions. We’ll authenticate the admin user and then execute a GraphQL mutation to create the product. Here’s how you can do it:

// app.test.jsx
import { useEffect } from "react";
import { json } from "@remix-run/node";
import { useActionData, useNavigation, useSubmit } from "@remix-run/react";
import {
    Page,
    Layout,
    Text,
    Card,
    Button,
    BlockStack,
    Box,
    List,
    Link,
    InlineStack,
} from "@shopify/polaris";
import { authenticate } from "../shopify.server";

export const loader = async ({ request }) => {
    await authenticate.admin(request);
    return null;
};

export const action = async ({ request }) => {
    const { admin } = await authenticate.admin(request);
    const color = ["Red", "Orange", "Yellow", "Green"][Math.floor(Math.random() * 4)];
    const response = await admin.graphql(`
        mutation populateProduct($input: ProductInput!) {
            productCreate(input: $input) {
                product {
                    id
                    title
                    handle
                    status
                    variants(first: 10) {
                        edges {
                            node {
                                id
                                price
                                barcode
                                createdAt
                            }
                        }
                    }
                }
            }
        }`,
        {
            variables: {
                input: {
                    title: `${color} Snowboard`,
                    variants: [{ price: Math.random() * 100, barcode: `barcode apply` }],
                },
            },
        }
    );
    const responseJson = await response.json();
    console.log("responseJson", responseJson);

    return json({
        product: responseJson.data.productCreate.product,
    });
};

This code snippet sets up the authentication and executes the GraphQL mutation to create a new product with a random color snowboard.

Step 2: Display Product Creation Interface

Now, let’s create the interface to trigger the product creation process and display the newly created product. We’ll use Polaris components for the UI elements. Here’s the code for the interface:

export default function Index() {
    const nav = useNavigation();
    const actionData = useActionData();
    const submit = useSubmit();
    const isLoading = ["loading", "submitting"].includes(nav.state) && nav.formMethod === "POST";
    const productId = actionData?.product?.id.replace("gid://shopify/Product/", "");

    useEffect(() => {
        if (productId) {
            shopify.toast.show("Product created");
        }
    }, [productId]);
    
    const generateProduct = () => submit({}, { replace: true, method: "POST" });

    return (
        <Page>
            <BlockStack gap="500">
                <Layout>
                    <Layout.Section>
                        <Card>
                            <BlockStack gap="500">
                                <InlineStack gap="300">
                                    <Button loading={isLoading} onClick={generateProduct}>
                                        Generate a product
                                    </Button>
                                    {actionData?.product && (
                                        <Button
                                            url={`shopify:admin/products/${productId}`}
                                            target="_blank"
                                            variant="plain"
                                        >
                                            View product
                                        </Button>
                                    )}
                                </InlineStack>
                                {actionData?.product && (
                                    <Box
                                        padding="400"
                                        background="bg-surface-active"
                                        borderWidth="025"
                                        borderRadius="200"
                                        borderColor="border"
                                        overflowX="scroll"
                                    >
                                        <pre style={{ margin: 0 }}>
                                            <code>{JSON.stringify(actionData.product, null, 2)}</code>
                                        </pre>
                                    </Box>
                                )}
                            </BlockStack>
                        </Card>
                    </Layout.Section>
                </Layout>
            </BlockStack>
        </Page>
    );
}

The useNavigation, useActionData, and useSubmit hooks are used to handle navigation, access action data, and handle form submissions, respectively.

This code sets up the UI interface with buttons to trigger product generation and view the created product.

Conclusion:

In conclusion, creating products in a Shopify Remix app using GraphQL mutations is a powerful way to add new products to your store programmatically. By following the steps outlined in this blog post, you can streamline the product creation process and enhance the overall user experience of your Shopify app.

Click to rate this post!
[Total: 0 Average: 0]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer ? with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket ?.

Recent Posts

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

1 day ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

3 days ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

4 days ago

Best Beginners Guide to Shopify Balance Account

If you are a Shopify admin, using a Shopify Balance Account for your business revenue…

4 days ago

8 Best Social Login Apps for Shopify Store in 2024

Running an eCommerce business can be incredibly demanding, leaving entrepreneurs little time to focus on…

4 days ago

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

5 days ago