๐งช Examples for getProduct()
Here are practical usage examples to help you understand how to use getProduct() effectively with typed metafields, error handling, and optional rendering logic.
๐น Basic Usage with Handleโ
import { getProduct } from "@/lib/NextShopKit/client";
const { data, error } = await getProduct({
handle: "solar-kit-9kw",
customMetafields: [
{ field: "custom.brand", type: "single_line_text" },
{ field: "custom.weight", type: "decimal" },
],
options: {
resolveFiles: true,
camelizeKeys: true,
renderRichTextAsHtml: false,
},
});
if (error || !data) {
console.error("โ Failed to load product:", error);
} else {
console.log("โ
Product:", data.title);
}
โ ๏ธ Error Handling Patternโ
Always check for error and data. If either is missing, show a fallback:
if (!data || error) {
return <p>Product not found or unavailable.</p>;
}
๐ฆ Accessing Parsed Metafieldsโ
<p>Brand: {data.metafields.custom.brand}</p>
<p>Weight: {data.metafields.custom.weight} kg</p>
๐จ Rendering Rich Text (HTML)โ
const { data } = await getProduct({
handle: "solar-kit-3kw",
customMetafields: [{ field: "custom.description", type: "rich_text" }],
options: {
renderRichTextAsHtml: true,
},
});
<div
className="product-description"
dangerouslySetInnerHTML={{
__html: data.metafields.custom.description,
}}
/>
๐ File Metafieldsโ
customMetafields: [
{ field: "custom.certificates", type: "File" }
],
options: {
resolveFiles: true
}
{
data.metafields.custom.certificates.map((file: any) => (
<a key={file.id} href={file.url} target="_blank">
{file.alt || "View File"}
</a>
));
}
โ Best Practicesโ
- Always use
handleoridโ never both - Wrap file downloads or rich text safely in the UI
- Use
camelizeKeysto make keys easier to work with - Prefer server-side fetching for better performance and SEO
- Use client-side approaches only when you need real-time updates
Next: Types โ
Description
Practical usage examples for getProduct(), including error handling, metafields, and rendering rich content.