import styles from "../styles/Home.module.css";
//import imageUrlBuilder from "@sanity/image-url";
import { useState, useEffect } from "react";
import { getPostAndAuthors } from "../lib/api";
export default function Home({ posts }) {
const [mappedPosts, setMappedPosts] = useState([]);
console.log("mappedPosts2: ", mappedPosts);
/* console.log(
"mappedPosts: ",
mappedPosts.map((p, index) => console.log(p[index]))
);
*/
useEffect(() => {
if (posts.length) {
setMappedPosts(
posts.map((p) => {
return {
...p,
};
})
);
} else {
setMappedPosts([]);
}
}, [posts]);
return (
<div>
<div>
<h3>Recent Posts:</h3>
{/* Sin _id == ^.author._ref no te va a hacer la relaciòn */}
{/*
`*[_type == "post"]{
title,
publishedAt,
'author': *[_type == "author" && _id == ^.author._ref && genre== 'comedia']{
genre,name, 'picture': image.asset->url}
}`
*/}
{/* Out:
[
{
"author": [
{
"genre": "comedia",
"name": "Cezar",
"picture": "https://cdn.sanity.io/images/9w4ss8xn/production/48ef72edee2dd89a71e272beea5721e40281d5a0-340x317.jpg"
}
],
"publishedAt": "2022-05-05T02:37:00.000Z",
"title": "Cuentos"
},
{
"author": [
{
"genre": "comedia",
"name": "Cezar",
"picture": "https://cdn.sanity.io/images/9w4ss8xn/production/48ef72edee2dd89a71e272beea5721e40281d5a0-340x317.jpg"
}
],
"publishedAt": "2022-05-06T02:36:00.000Z",
"title": "Tormenta"
},
{
"author": [],
"publishedAt": "2022-05-04T02:38:00.000Z",
"title": "Rios del Desierto"
}
]
*/}
<div>
{mappedPosts.map((p, index) => (
<div className={styles.post} key={index}>
<h4>{p.author.length > 0 ? p.title : null}</h4>
{p.author.map((a, index) => (
<p key={index}>{a.name}</p>
))}
</div>
))}
</div>
</div>
</div>
);
}
export const getServerSideProps = async () => {
const posts = await getPostAndAuthors();
return {
props: {
posts,
},
};
};
/* export async function getStaticPaths() {
const allPosts = await getAllPostsWithSlug();
return {
paths:
allPosts?.map((post) => ({
params: {
slug: post.slug,
},
})) || [],
fallback: true,
};
} */
Comments