Remix

Implementing Prisma Pagination with Skip and Take in a Shopify Remix App

Pagination is an essential feature in web applications that handle large datasets. It improves the user experience by dividing content into manageable chunks, preventing long loading times, and offering easy navigation. In a Shopify Remix app, implementing pagination can be done efficiently using Prisma with the skip and take methods. This blog will guide you through the process of setting up pagination in your Shopify Remix app using Prisma.

What is Prisma?

Prisma is an open-source ORM (Object-Relational Mapping) tool that simplifies database access and management in Node.js and TypeScript applications. It provides a type-safe query builder that allows developers to interact with databases using an intuitive API.

Understanding Skip and Take

In Prisma, the skip and take methods are used to implement pagination:

  • Skip: Specifies the number of records to skip from the beginning of the result set.
  • Take: Specifies the number of records to take (retrieve) after the skipped records.

By combining these two methods, you can efficiently retrieve a specific subset of data from your database.

Steps to Implement Prisma Pagination with Skip and Take in a Shopify Remix App:

Step 1: Setting Up the Loader Function

The loader function in Remix is used to fetch data before rendering a page. Here’s how to set it up for pagination:

// app.products.jsx
 export async function loader({ request }) {
    const { session, admin } = await authenticate.admin(request);
    const url = new URL(request.url);
    const searchParam = url.searchParams;
    const skip = Number(searchParam.get("skip")) || 0;
    const take = Number(searchParam.get("take")) || 5;

    // Fetch total count of products
    const totalCount = await db.product.count({
        where: { shop: session.shop },
    });

    // Fetch paginated products
    const products = await db.product.findMany({
        skip: skip,
        take: take,
        where: { shop: session.shop },
        orderBy: { id: "desc" },
    });

    return json({ products, totalCount, skip, take });
}

Explanation:

  • Authentication: We authenticate the admin to ensure secure access.
  • Query Parameters: Retrieve skip (the number of records to skip) and take (the number of records to fetch) from the URL query parameters. If not provided, default to 0 for skip and 5 for take.
  • Total Count: Use Prisma to count the total number of products. This count helps calculate the total number of pages.
  • Product Fetching: Fetch the subset of products using Prisma’s findMany method with skip and take parameters. This limits the number of records retrieved based on the current page.

Step 2: Implementing Pagination in the Component

In the React component, handle the pagination logic and render the paginated data using Shopify Polaris’s IndexTable component.

function Products() {
    const { products, totalCount, skip, take, searchQuery } = useLoaderData();
    const navigate = useNavigate();
    const totalPages = Math.ceil(totalCount / take);
    const currentPage = Math.floor(skip / take) + 1;
    const [searchValue, setSearchValue] = useState(searchQuery || "");
    const formattedQuery = searchValue.replace(/\s+/g, '-');

    const pagination = {
        previous: {
            disabled: currentPage <= 1,
            link: currentPage > 1 ? `/app/products/?query=${formattedQuery}&skip=${Math.max(skip - take, 0)}&take=${take}` : null,
        },
        next: {
            disabled: currentPage >= totalPages,
            link: currentPage < totalPages ? `/app/products/?query=${formattedQuery}&skip=${skip + take}&take=${take}` : null,
        },
    };

    return (
        <Page title="Product Management">
            <IndexTable
                resourceName={{ singular: "product", plural: "products" }}
                itemCount={products.length}
                headings={[
                    { title: "id" },
                    { title: "Title" },
                ]}
               
                pagination={{
                    hasPrevious: currentPage > 1,
                    onPrevious: () => {
                        if (pagination.previous.link) {
                            navigate(pagination.previous.link);
                        }
                    },
                    hasNext: currentPage < totalPages,
                    onNext: () => {
                        if (pagination.next.link) {
                            navigate(pagination.next.link);
                        }
                    },
                }}
            >
                {products.map(({ id, productImage }, index) => (
                    <IndexTable.Row id={id} key={id}>
                        
                        <IndexTable.Cell>{id}</IndexTable.Cell>
                        <IndexTable.Cell>{productTitle}</IndexTable.Cell>
                        
                    </IndexTable.Row>
                ))}
            </IndexTable>
        </Page>
    );
}
  • Compute the total number of pages and the current page based on the skip and take values. This calculation helps in creating pagination controls.
  • Set up the links for navigating between pages. Ensure that previous and next links are disabled appropriately based on the current page.
  • Use the IndexTable component to display the products. Include pagination controls to allow users to navigate between pages.

Conclusion:

Implementing pagination with Prisma’s skip and take parameters in a Shopify Remix app helps manage large datasets efficiently. By fetching only a subset of data and providing intuitive navigation controls, you improve both performance and user experience.

Click to rate this post!
[Total: 1 Average: 5]
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

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

21 hours ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

22 hours ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

2 weeks ago