Move product catalog to Payload CMS
Products now come from Payload's new "products" collection instead of a hardcoded catalog, same pattern already used for blog posts: - lib/payload.ts: getProducts()/getProductBySlug() (server-side fetch, 60s ISR) - New /api/products route so client components (CartContent, RelatedProducts) can reach the same data without a server-only import - lib/products.ts: useProducts() hook replacing the old PRODUCTS record - ProductGrid (/shop) fetches server-side directly; now shows all catalog products except notizbuch-klarheit (matches Figma's 4-card page-shop-overview — still cross-sold via RelatedProducts) - ProductSpotlight and /todo-cards' Pricing now pull price/photo from the same CMS product instead of a separately hardcoded "12,90 €", so the two can't silently drift apart - formatPrice moved to a new lib/format.ts (plain, no "use client") — Server Components can't call functions exported from a "use client" module directly, which lib/products.ts now is because of the hook Also fixes two unrelated bugs surfaced along the way: the add-to-cart button visibly resizing when its "Hinzugefügt ✓" success state showed (fixed with a CSS-grid text stack sized to the wider of the two strings), and removes the now-unused local product images from public/.
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
// Plain utility, no client-only behavior — kept out of lib/products.ts
|
||||
// (which is "use client" for its useProducts() hook) specifically so
|
||||
// Server Components can still call it directly. Any export from a
|
||||
// "use client" module becomes a client-only reference as far as Next.js's
|
||||
// RSC boundary is concerned, even a pure function with zero hooks — a
|
||||
// Server Component importing formatPrice from products.ts fails at
|
||||
// runtime with "Attempted to call formatPrice() from the server but
|
||||
// formatPrice is on the client."
|
||||
export function formatPrice(value: number): string {
|
||||
return `${value.toFixed(2).replace(".", ",")} €`;
|
||||
}
|
||||
@@ -55,3 +55,60 @@ export async function getBlogPosts(limit = 3): Promise<BlogPost[]> {
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
|
||||
// Frontend-facing shape — `id` is Payload's `slug` field, not its numeric
|
||||
// row id. Cart items are stored in localStorage keyed by this string (see
|
||||
// lib/cart.ts), so slugs were chosen in the Products collection to match
|
||||
// the ids the old hardcoded catalog used ("todo-karten" etc.) — switching
|
||||
// to numeric ids here would silently orphan every existing shopper's cart.
|
||||
export type Product = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
price: number;
|
||||
image: string;
|
||||
href: string | null;
|
||||
};
|
||||
|
||||
type PayloadProduct = {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string | null;
|
||||
price: number;
|
||||
image: { url: string } | number | null;
|
||||
detailHref: string | null;
|
||||
};
|
||||
|
||||
export async function getProducts(): Promise<Product[]> {
|
||||
const params = new URLSearchParams({
|
||||
"where[tenant.slug][equals]": TENANT_SLUG,
|
||||
sort: "sortOrder",
|
||||
depth: "2",
|
||||
limit: "100",
|
||||
});
|
||||
|
||||
const res = await fetch(`${PAYLOAD_URL}/api/products?${params}`, {
|
||||
next: { revalidate: 60 },
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.error(`getProducts: Payload returned ${res.status} ${res.statusText}`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const data: { docs?: PayloadProduct[] } = await res.json();
|
||||
const docs = Array.isArray(data.docs) ? data.docs : [];
|
||||
return docs.map((product) => ({
|
||||
id: product.slug,
|
||||
name: product.name,
|
||||
description: product.description ?? "",
|
||||
price: product.price,
|
||||
image: typeof product.image === "object" && product.image ? product.image.url : "",
|
||||
href: product.detailHref || null,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getProductBySlug(slug: string): Promise<Product | null> {
|
||||
const products = await getProducts();
|
||||
return products.find((p) => p.id === slug) ?? null;
|
||||
}
|
||||
|
||||
+44
-60
@@ -1,65 +1,49 @@
|
||||
// Small in-code product catalog — this project has no commerce backend,
|
||||
// so cart items (stored in localStorage as {id, qty} pairs, see cart.ts)
|
||||
// need somewhere to look up name/price/photo/description by id. Only
|
||||
// "todo-karten" has a real detail page (/todo-cards) right now; the
|
||||
// other four exist because they're shown in Figma's page-cart "Passt
|
||||
// perfekt dazu" row and are addable to the cart from there, same as the
|
||||
// real product — they just don't have their own detail pages built yet
|
||||
// (matching the project's established pattern of cross-linking to
|
||||
// not-yet-built routes rather than leaving buttons disconnected).
|
||||
export type Product = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
price: number;
|
||||
image: string;
|
||||
href?: string;
|
||||
};
|
||||
"use client";
|
||||
|
||||
export const PRODUCTS: Record<string, Product> = {
|
||||
"todo-karten": {
|
||||
id: "todo-karten",
|
||||
name: "ToDo-Karten – Set",
|
||||
description: "50 ToDo-Karten für mehr Fokus und Klarheit im Alltag.",
|
||||
price: 12.9,
|
||||
image: "/product-todo-karten.png",
|
||||
href: "/todo-cards",
|
||||
},
|
||||
"notizbuch-klarheit": {
|
||||
id: "notizbuch-klarheit",
|
||||
name: "Notizbuch – Klarheit",
|
||||
description: "Dein Begleiter für Gedanken, Notizen und neue Perspektiven.",
|
||||
price: 9.9,
|
||||
image: "/product-notizbuch-klarheit.png",
|
||||
},
|
||||
wochenplaner: {
|
||||
id: "wochenplaner",
|
||||
name: "Wochenplaner – Überblick",
|
||||
description: "Behalte deine Woche im Blick und setze klare Prioritäten.",
|
||||
price: 14.9,
|
||||
image: "/product-wochenplaner.png",
|
||||
},
|
||||
"notizbuch-fokus": {
|
||||
id: "notizbuch-fokus",
|
||||
name: "Notizbuch – Fokus",
|
||||
description: "Für mehr Konzentration und einen klaren Kopf im Alltag.",
|
||||
price: 9.9,
|
||||
image: "/product-notizbuch-fokus.png",
|
||||
},
|
||||
zielkarten: {
|
||||
id: "zielkarten",
|
||||
name: "Zielkarten – Set",
|
||||
description: "Definiere deine Ziele und behalte sie fest im Blick.",
|
||||
price: 11.9,
|
||||
image: "/product-zielkarten.png",
|
||||
},
|
||||
};
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Product } from "./payload";
|
||||
|
||||
export const RELATED_PRODUCT_IDS = ["wochenplaner", "notizbuch-fokus", "zielkarten"];
|
||||
export type { Product };
|
||||
|
||||
// Shop overview grid order — mirrors page-shop-overview in Figma.
|
||||
export const SHOP_PRODUCT_IDS = ["todo-karten", "wochenplaner", "notizbuch-fokus", "zielkarten"];
|
||||
// Products now live in Payload's "products" collection (tenant
|
||||
// einfach-produktiv), not a hardcoded catalog — see lib/payload.ts's
|
||||
// getProducts() for the server-side fetch. Client components (CartContent,
|
||||
// RelatedProducts) can't call that directly the way a Server Component
|
||||
// can, so this hook fetches the same-origin /api/products proxy instead,
|
||||
// with a tiny module-level cache so /cart's two consumers (CartContent +
|
||||
// RelatedProducts) share one request instead of firing it twice.
|
||||
let cache: Product[] | null = null;
|
||||
let inflight: Promise<Product[]> | null = null;
|
||||
|
||||
export function formatPrice(value: number): string {
|
||||
return `${value.toFixed(2).replace(".", ",")} €`;
|
||||
async function fetchProducts(): Promise<Product[]> {
|
||||
if (cache) return cache;
|
||||
if (!inflight) {
|
||||
inflight = fetch("/api/products")
|
||||
.then((res) => (res.ok ? res.json() : []))
|
||||
.then((data: Product[]) => {
|
||||
cache = data;
|
||||
return data;
|
||||
})
|
||||
.catch(() => []);
|
||||
}
|
||||
return inflight;
|
||||
}
|
||||
|
||||
// Starts empty (SSR-safe — matches useCart()'s pattern of a safe default
|
||||
// that fills in after a client-only effect, see lib/cart.ts) and updates
|
||||
// once the fetch resolves.
|
||||
export function useProducts(): Product[] {
|
||||
const [products, setProducts] = useState<Product[]>(cache ?? []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetchProducts().then((data) => {
|
||||
if (!cancelled) setProducts(data);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return products;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user