Home > Mobile >  How to map a collection fetched from Strapi through getStaticProps in a Next.js component
How to map a collection fetched from Strapi through getStaticProps in a Next.js component

Time:08-06

I am following a YouTube tutorial on how to make a simple blog using Next.js and Strapi. Below is the code for fetching post data from Strapi. It does not work because the .map function used in the Home function can only be used on arrays. I am fetching an object from Strapi. How do I get around this? And also, if you view the YouTube tutorial that I am following (link), at the 30 minutes mark, you can see that the person is using the .map function even though "posts" is an object. How does that work?

export default function Home({ posts }) {
  return (
    <div>
      {posts &&
        posts.map((post) => (
          <div key={post.id}>
            <p>{post.Title}</p>
          </div>
        ))}
    </div>
  );
}

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/api/posts");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

CodePudding user response:

In the video tutorial at this point it shows an array of objects. map() iterates through each item in the array, returning the object as the variable post.

It is hard to answer why Strapi isn't returning an array without showing what is actually returned by posts. From checking the API docs it looks like the array may be under the key data. It also looks like if you get 1 entry, it will not be in an array (in which case you could either throw it in one yourself by sandwiching it in brackets... or just not use map().

CodePudding user response:

I think you're just hitting the wrong endpoint there (depends on which version of Strapi you instantiated):

Strapi v3

for below v4 as illustrated in the video you're following it's http://localhost:1337/posts, not http://localhost:1337/api/posts

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/posts");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

I guess http://localhost:1337/api/posts just returns an error string or object..

Strapi v4

If however you're using Strapi v4 then the response is wrapped in a proper JSON:API format - which means that you have a data object that holds the array. (see https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#endpoints)

In this case you can iterate through the array on the data object


    {posts &&
        posts.data.map((post) => (
          <div key={post.id}>
            <p>{post.Title}</p>
          </div>
        ))}

Generally, if you run into this kind of trouble check the Network tab of your browser to see what response you actually receive with the XHR request or log the result somehow to inspect the problem and determine a path forward.

  • Related