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

Magento 2: How To Call JS on the Checkout Page?

Hello Magento mates, Today we will learn to add a call JS on the checkout…

1 day ago

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

2 days ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

3 days ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

3 days ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

5 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

1 week ago