import { useLoaderData, useFetcher } from "@remix-run/react";
import { json } from "@remix-run/node";
import { authenticate } from "../shopify.server";
import {
Page,
Layout,
Text,
Card,
Button,
DataTable,
Thumbnail,
} from "@shopify/polaris";
export const loader = async ({ request }) => {
const { admin } = await authenticate.admin(request);
const response = await admin.graphql(
`#graphql
{
products(first: 10) {
edges {
node {
id
title
handle
status
images(first: 1) {
edges {
node {
originalSrc
altText
}
}
}
variants(first: 10) {
edges {
node {
id
price
barcode
createdAt
}
}
}
}
}
}
}`
);
const responseJson = await response.json();
return json(responseJson.data);
};
export default function Products() {
const data = useLoaderData();
const fetcher = useFetcher();
const products = data.products.edges;
const handleDelete = async (productId) => {
await fetcher.submit(
{ productId },
{ method: "DELETE", action: "/products/delete" }
);
};
const rows = products.map(({ node: product }) => [
<Thumbnail
source={product.images.edges[0]?.node.originalSrc || ""}
alt={product.images.edges[0]?.node.altText || "Product Image"}
/>,
product.title,
product.status,
product.variants.edges[0]?.node.price || "",
<Button
onClick={() => (window.location.href = `/admin/products/${product.id}`)}
>
Edit
</Button>,
<Button destructive onClick={() => handleDelete(product.id)}>
Delete
</Button>,
]);
return (
<Page fullWidth>
<Layout>
<Layout.Section>
<Card>
<Text as="h2" variant="headingMd">
Products List
</Text>
<DataTable
columnContentTypes={["text", "text", "text", "text", "text", "text"]}
headings={["Image", "Title", "Status", "Price", "Edit", "Delete"]}
rows={rows}
/>
</Card>
</Layout.Section>
</Layout>
</Page>
);
}
Leave a Reply