Edit Shopify Products in a Custom App with Remix.js and Polaris | Shopify App Development

In the ever-evolving landscape of eCommerce, providing merchants with tools that simplify product management is crucial. Shopify, a leading eCommerce platform, offers extensive APIs that allow developers to build custom apps tailored to specific business needs. One of the most common requirements for Shopify apps is the ability to edit product details, such as titles, prices, and variants. In this article, we will explore how to create a custom Shopify app that enables merchants to edit their products using Remix.js and Shopify Polaris. By the end of this tutorial, you will have a solid understanding of how to implement product editing functionality in a custom Shopify app, leveraging the power of modern web development tools.

Why Use Remix.js and Polaris for Shopify App Development?

Before we dive into the implementation, let’s discuss why Remix.js and Shopify Polaris are excellent choices for Shopify app development:

  • Remix.js: Remix is a React-based framework that focuses on server-side rendering (SSR) and optimized data loading, making it ideal for building fast, dynamic web applications. Its ability to handle complex data interactions efficiently makes it a perfect fit for a custom Shopify app.
  • Shopify Polaris: Polaris is Shopify’s design system that provides a set of React components to ensure your app’s UI is consistent with Shopify’s admin interface. By using Polaris, you can create a seamless and professional user experience, ensuring that your app feels like a natural extension of Shopify.

Setting Up Your Development Environment

Before we begin, let’s set up the necessary tools and environment to build our Shopify app.

  1. Install Node.js: Ensure that Node.js and npm (Node Package Manager) are installed on your system.
  2. Create a Shopify App with Remix.js: Use the Shopify CLI to create a new app with Remix.js as the frontend framework:bashCopy codeshopify app create node -t remix This command initializes a new Shopify app using Remix.js, setting the stage for our product editing functionality.
  3. Install Shopify Polaris: Navigate to your app’s directory and install Polaris components:bashCopy codenpm install @shopify/polaris
  4. Set Up Remix.js: Make sure that your Remix.js environment is properly configured, including setting up routes, loaders, and actions for managing data and handling user interactions.

Fetching Product Data from the Shopify API

To allow merchants to edit product details, the first step is to fetch the relevant product data from the Shopify API.

Step 1: Configure API Access

Ensure that your Shopify app is configured to access the Shopify API. In your shopify.config.js file, include the necessary API credentials:

javascriptCopy codemodule.exports = {
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET,
  scopes: ['read_products', 'write_products'],
  shop: process.env.SHOPIFY_SHOP,
  accessToken: process.env.SHOPIFY_ACCESS_TOKEN,
};

Make sure to store your API key and access token securely in environment variables.

Step 2: Create a Function to Fetch Product Details

Next, create a utility function to fetch product details, including its variants, from the Shopify API. In your utils directory, create a file named fetchProduct.js:

javascriptCopy codeimport { gql } from 'graphql-request';
import { shopifyClient } from './shopifyClient';

export async function fetchProduct(productId) {
  const query = gql`
    query GetProduct($id: ID!) {
      product(id: $id) {
        id
        title
        variants(first: 10) {
          edges {
            node {
              id
              title
              price
              inventoryQuantity
            }
          }
        }
      }
    }
  `;

  const variables = { id: productId };
  const response = await shopifyClient.request(query, variables);
  return response.product;
}

This function uses a GraphQL query to retrieve the product details and its variants from Shopify.

Displaying and Editing Product Details

With the product data retrieved, the next step is to display it in a form where users can edit the details.

Step 1: Create the Product Edit Page

Create a new component, ProductEditPage.jsx, in your components or pages directory. This component will display the product and its variants, allowing users to edit them:

javascriptCopy codeimport { Page, Card, FormLayout, TextField, Button, Stack } from '@shopify/polaris';
import { useLoaderData, useFetcher } from '@remix-run/react';
import { fetchProduct } from '../utils/fetchProduct';

export async function loader({ params }) {
  const productId = params.productId;
  const product = await fetchProduct(productId);
  return product;
}

function ProductEditPage() {
  const product = useLoaderData();
  const fetcher = useFetcher();

  const handleInputChange = (variantId, field, value) => {
    fetcher.submit(
      { variantId, field, value },
      { method: 'post', action: `/products/${product.id}/edit` }
    );
  };

  return (
    <Page title={`Edit Product: ${product.title}`}>
      <Card sectioned>
        {product.variants.edges.map(({ node: variant }) => (
          <Stack vertical key={variant.id}>
            <FormLayout>
              <TextField
                label="Variant Title"
                value={variant.title}
                onChange={(value) => handleInputChange(variant.id, 'title', value)}
              />
              <TextField
                label="Price"
                value={variant.price}
                type="number"
                onChange={(value) => handleInputChange(variant.id, 'price', value)}
              />
              <TextField
                label="Inventory Quantity"
                value={variant.inventoryQuantity}
                type="number"
                onChange={(value) => handleInputChange(variant.id, 'inventoryQuantity', value)}
              />
            </FormLayout>
          </Stack>
        ))}
      </Card>
      <Button primary submit>Save Changes</Button>
    </Page>
  );
}

export default ProductEditPage;

In this code:

  • FormLayout and TextField: These Polaris components are used to create input fields for editing variant details like the title, price, and inventory quantity.
  • handleInputChange Function: This function triggers an API call to update the product variant whenever an input field is changed.

Step 2: Implement the Update Action

Now, create the action that handles updating the product variant. In your routes directory, create a file named products.edit.js:

javascriptCopy codeimport { redirect } from '@remix-run/node';
import { shopifyClient } from '../../utils/shopifyClient';
import { gql } from 'graphql-request';

export async function action({ request, params }) {
  const formData = await request.formData();
  const variantId = formData.get('variantId');
  const field = formData.get('field');
  const value = formData.get('value');

  const mutation = gql`
    mutation UpdateProductVariant($id: ID!, $input: ProductVariantInput!) {
      productVariantUpdate(id: $id, input: $input) {
        productVariant {
          id
        }
      }
    }
  `;

  const input = { [field]: value };
  await shopifyClient.request(mutation, { id: variantId, input });

  return redirect(`/products/${params.productId}/edit`);
}

This action performs the following steps:

  • Receive the Variant ID and Field Data: It receives the variant ID, field name, and updated value from the form data.
  • Update the Product Variant: It uses a GraphQL mutation to update the product variant in Shopify.
  • Redirect: After updating, the user is redirected back to the product edit page.

Enhancing the User Experience

To provide a better user experience, consider adding the following enhancements:

  1. Validation and Error Handling: Implement validation for the input fields and handle errors gracefully by displaying error messages to the user if the update fails.
  2. Optimistic UI Updates: Update the UI immediately after a change is made, without waiting for the server response, to make the app feel more responsive.
  3. Confirmation Dialog: Before making changes, especially for critical fields like price or inventory, display a confirmation dialog to avoid accidental updates.
  4. Loading States: Use loading indicators to show that data is being fetched or that an update is in progress, enhancing the overall user experience.

Testing and Deployment

After implementing the product editing functionality, thoroughly test it to ensure it works as expected:

  • Functionality: Verify that all product details are fetched correctly and that updates are applied as expected.
  • User Experience: Ensure that the UI is responsive and intuitive, providing clear feedback to users during the editing process.
  • Error Scenarios: Test how the app handles errors, such as failed API requests or invalid data inputs.

Once testing is complete, deploy your Shopify app using the Shopify CLI:

bashCopy codeshopify app deploy

Conclusion

Editing Shopify products in a custom app using Remix.js and Polaris is a powerful way to extend the capabilities of Shopify stores, providing merchants with intuitive tools for managing their inventory. By following this tutorial, you’ve learned how to fetch product data from the Shopify API, display it using Polaris components, and implement functionality to edit product variants.

As you continue to develop Shopify apps, mastering these tools will enable you to create high-quality, custom solutions that meet the needs of Shopify merchants. Whether you’re building simple management tools or complex eCommerce applications, the combination of Remix.js and Polaris offers the flexibility

Leave a Reply

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