2

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": "[email protected]",
"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.

2 Answers 2

1

If you are using Next.js and want to take full advantage of static rendering I would advise avoiding getStaticProps if you can.

Here is a working example using pure components and no props at all.

const Home = () => {
  const [posts, setPosts] = React.useState(null);

  const getPosts = async() => {
    const res = await fetch("http://localhost:1337/posts");
    const json = await res.json();
    setPosts(json);
  }

  if(!posts){
    getPosts();
  }

  return (
    <div>
      {posts ? posts.map((post) => (
        <div key={post.title}>
            <h2>{post.title}</h2>
        </div>
      )) : (
        <div>Loading...</div>
      )}
    </div>
  )
}

export default Home;
Sign up to request clarification or add additional context in comments.

1 Comment

Clean code and nicely explained, thanks 👍
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.