Search code examples
next.jsstrapiheadless-cms

Can't fetch data from Strapi API to next.js frontend


I'm tried strapi and next.js to make a blog site. Here is next.js for frontend code

import Head from 'next/head'
import styles from '../styles/Home.module.css'

export default function Home({ posts }) {

  return (
    <div>
      {posts && 
      
      posts.map((posts) => (

        <div key={post.id}>
            <h2>{posts.title}</h2>
        </div>
      ))}
    </div>
  );
}



export async function getstaticProps() {

  //get post from our API

  const res = await fetch("http://localhost:1337/posts");
  const posts = await res.json();

  return {
    props: { posts },
  };

}

and Here is Strapi API Json data

[
{
"id": 1,
"title": "Hello Everyone",
"slug": "hello-everyone",
"content": "Hello All.",
"users_permissions_user": {
"id": 4,
"username": "tanha",
"email": "tanha@test.com",
"provider": "local",
"confirmed": true,
"blocked": false,
"role": 1,
"created_at": "2021-03-12T06:02:44.726Z",
"updated_at": "2021-03-12T06:03:54.507Z"
},
"published_at": "2021-03-11T19:37:02.117Z",
"created_at": "2021-03-11T19:36:46.663Z",
"updated_at": "2021-03-12T11:48:57.275Z"
}
]

What is the problem in here? I was tried but found no errors in here. But can't fetch data into frontend to show.


Solution

  • getstaticProps should be in different case -> getStaticProps, other than that your code looks fine.