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

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.

Previous Article

What is Locksmith Shopify App?

Next Article

How to Delete an Existing Foreign Key in Magento 2 Installer?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨