#๐ŸŸฉ Content collections and referenced data

17 messages ยท Page 1 of 1 (latest)

spring root
#

if i console.log(products)
iv got this
why undefined...

heady osprey
#

I'm surprised you're not getting a TS error when doing this:

product.data.category = await getEntry(product.data.category);

The shape of product.data.category is {collection: "categories", id: "..."} no "data" property.
getEntry() returns {collection: "categories", id: "...", data: {...}
So by assigning the results to product.data.category, you're not getting "data".

spring root
#

but why 1st dev run page all are fine...

#

can't understand these collections (

#

i cant even render image

heady osprey
spring root
#

no.. i just want <img />
im doing what docs says

spring root
#

Now i need to figure out the categories

#
const singleproduct = await getEntry('products', 'prl001');
const singlecategory = await getEntry(singleproduct.data.category);

this works fine for single product
but how i get category entry for every product in products collection?
@heady osprey can u help me?

heady osprey
#

I'd create a new array of products with categories, something like:

type ProductCat = {
    name: string
    category: string
    price: number
}
let productsCat: ProductCat[] = []
for (let product of products) {
    category = await getEntry(product.data.category);
    productCat.push({name: prooduct.name, category: category.name, price: product.price})
}
spring root
#

hmm

#

interesting solution

#

works fine...

#

but on any changes in collection i have to correct this. not good

heady osprey
#

You could get more creative:

interface ProductCat extends z.infer<typeof products.data> {
    categoryName: string
}
let productsCat: ProductCat[] = []
for (let product of products) {
    category = await getEntry(product.data.category);
    productCat.push({...prooduct.data, categoryName: category.name})
}

untested of course, but you should be able to get that working

spring root
#

Yeah. Support-ai give me the same.. it works