From 2b78713b6755cfca310eacf75c2b10d59daa5569 Mon Sep 17 00:00:00 2001 From: Vula Builder Date: Tue, 28 Jul 2026 07:32:27 +0000 Subject: [PATCH] Deploy --- src/hooks/useFeaturedProducts.ts | 65 ++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/hooks/useFeaturedProducts.ts diff --git a/src/hooks/useFeaturedProducts.ts b/src/hooks/useFeaturedProducts.ts new file mode 100644 index 0000000..e7fe691 --- /dev/null +++ b/src/hooks/useFeaturedProducts.ts @@ -0,0 +1,65 @@ +'use client' +import { useState, useEffect } from 'react' +import type { MedusaProduct } from './useMedusaProducts' + +interface UseFeaturedProductsResult { + products: MedusaProduct[] + loading: boolean + isLoading: boolean + error: string | null +} + +export function useFeaturedProducts(fallbackLimit = 8): UseFeaturedProductsResult { + const [products, setProducts] = useState([]) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + + useEffect(() => { + let cancelled = false + + async function load() { + try { + // Step 1: fetch curated IDs from Vula CMS + const cmsRes = await fetch('/api/content/featured_products', { cache: 'no-store' }) + let ids: string[] = [] + if (cmsRes.ok) { + const cmsData = await cmsRes.json() + const items: Array<{ data: { product_ids?: unknown } }> = cmsData.items ?? [] + const first = items[0]?.data?.product_ids + ids = Array.isArray(first) ? (first as string[]).filter(Boolean) : [] + } + + let fetched: MedusaProduct[] = [] + if (ids.length > 0) { + // Step 2: hydrate from Medusa by ID + const params = new URLSearchParams() + ids.forEach((id) => params.append('id[]', id)) + params.set('limit', String(ids.length)) + const medusaRes = await fetch(`/api/medusa/products?${params}`) + if (medusaRes.ok) { + const data = await medusaRes.json() + fetched = data.products ?? [] + } + } + + if (fetched.length === 0) { + // Step 3: fallback — latest products from Medusa + const fallbackRes = await fetch(`/api/medusa/products?limit=${fallbackLimit}`) + if (fallbackRes.ok) { + const data = await fallbackRes.json() + fetched = data.products ?? [] + } + } + + if (!cancelled) { setProducts(fetched); setLoading(false) } + } catch (err) { + if (!cancelled) { setError(String(err)); setLoading(false) } + } + } + + load() + return () => { cancelled = true } + }, [fallbackLimit]) + + return { products, loading, isLoading: loading, error } +}