I am trying to map through an array and display names so I can eventually dynamically route to pages for each person. The array is coming back as undefined despite it being declared. So that is why .map is not working. But where am I going wrong here?
I have this code for an array
/lib/api
export async function getCastDetails() {
const members = (
{
id: "1",
name: "name one"
},
{
id: "2",
name: "name two"
},
{
id: "3",
name: "name three"
}
)
return members;
}
and I have this code to map through the array and display the names on a page
import { getCastDetails } from "@/lib/api";
export async function getStaticProps() {
const castData = await getCastDetails();
return {
props: {
castData,
}
}
}
const CastCarousel = ({ castData }) => {
console.log(castData);
return (
<div>
{castData.map(member => (
<div
key={member.id}
>
<a>{member.name}</a>
</div>
))}
</div>
)
}
export default CastCarousel
I am then displaying on my index page
EDIT:
I believe I need to pass castData through my component on my index page, but I cannot figure out how to do that.
Here is what my index page looks like
import CastCarousel from "@/components/CastCarousel"
const Cast = () => {
return (
<main>
<div className="flex flex-col justify-center items-center h-screen">
<div>
<h1
className="text-6xl relative"
>Explore The Guys</h1>
</div>
<div className="">
<CastCarousel/>
</div>
</div>
</main>
)
}
export default Cast
2
Answers
Arrays use
[]
and not()
. I your case this function should be:otherwise what is happening is that
members
is assigned the last object in that enumeration (the one with id 3) and that’s why you get the.map
error because it is an object and not an array.The issue arises because the
getCastDetails
function is not returning an array but a single object due to a syntax error. The curly braces{}
are used for creating objects, and when you want to return multiple objects in an array, you should enclose them in square brackets[]
.Here is how you should modify your
getCastDetails
function to return an array of objects:With this change, your
castData
should be an array, and the.map()
function should work as expected.Additionally, ensure that when you use
CastCarousel
on your index page, you passcastData
as a prop:This will ensure that
CastCarousel
receivescastData
which is an array and can be mapped over to display the members’ names. Remember thatgetStaticProps
is typically used in Next.js to fetch data at build time, so you need to ensure it’s called and the data is passed correctly to the component.