0
votes

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?

2
You omitted where data comes from, I assume for simplicity. Make sure it is actually an array.Dominik

2 Answers

1
votes

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;
-1
votes
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