Reputation: 147
I've seen many questions relating to issues with getInitialProps
and getStaticProps
but haven't been able to solve my own.
I'm merely trying to load some json data (I console.logged it and know it's not undefined) and pass it to my Main
component:
import Card from "./components/Card";
import data from "../data/data.json";
const Main = ({ cards }) => {
return (
<div}>
{cards.map((card) => {
<Card key={card.id} card={card} />;
})}
</div>
);
};
Main.getInitialProps = async (context) => {
return {
props: { cards: data },
};
};
export default Main;
TypeError: Cannot read property 'map' of undefined
I tried with getStaticProps
as well, same issue.
What am I doing wrong?
Upvotes: 0
Views: 1662
Reputation: 11
Page.getInitialProps = async (ctx) => {
const res = await fetch('https://api.url.com')
const json = await res.json()
return { stars: json.stargazers_count }
}
you have to change this
return {
props: { cards: data },
};
should use this:
return { cards: data }
for more you look : docs
Upvotes: 0
Reputation: 6313
According to the docs this should work:
import Card from "./components/Card";
import data from "../data/data.json";
const Main = ({ cards }) => {
return (
<div}>
{cards.map((card) => {
<Card key={card.id} card={card} />;
})}
</div>
);
};
Main.getInitialProps = async (context) => {
// await for `data`
return {
cards: data,
};
// ^-- note the change, you nested your object inside a `props` property
};
export default Main;
Upvotes: 1