skip to Main Content

I am following a Next.Js tutorial about server-side rendering. The solution works if I add the fetch in the same index.js file.

/pages/posts/index.js:

    export default function index({ posts }) {
  return (
    <div>
      <h2>Posts API</h2>
      <ul>
        {posts.map((post) => {
          return <li key={post.id}>{post.title}</li>;
        })}
      </ul>
    </div>
  );
}

export async function getServerSideProps() {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts`);
  const posts = await res.json();
  console.log(posts);
  return { props: { posts } };
}

However, when I break the code in a component like this

file: /pages/posts/index.js

import { userGetPosts } from '../lib/posts';



export async function getServerSideProps(){
  const posts = await userGetPosts();
  //const data =   JSON.parse(JSON.stringify( posts))
  console.log(posts);
  return { props: { posts } };
}

export default function Home({ posts }) {
  return (
    <Layout home>
      <Head>
        <title>{siteTitle}</title>
      </Head>
      
      <section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}>
        <h2 className={utilStyles.headingLg}>Blog</h2>
        <ul>
          {/* ENABLING THIS throws error */}
        {/* {posts.map((post) => {
          return <li key={post.id}>{post.title}</li>;
        })} */}
      </ul>
      </section>
    </Layout>
  );
}

../lib/posts.js

export async  function userGetPosts (){
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts`);
  {/* Need to convert to text else the index.js get array of objects*/}
  const posts = await res.text();
  //console.log(posts);
  return { props: { posts } };
};

The console.log(posts) shows that the response is received but when I try and do posts.map, I get an error on the browser –
TypeError posts.map is not a function

I tried using JSON.parse(posts) because, from the component, I am passing as text, but that does not help.

Any ideas?

2

Answers


  1. Try By Writing This Code

     {post && post.length > 1 ? posts.map((post) => {
              return <li key={post.id}>{post.title}</li>;
            } : null )}
    

    If there is No Any Rendring Then There is No Data inside Post

    Login or Signup to reply.
  2. Change the return type of userGetPosts as below, so getServerSideProps returns { props: { posts } } and not { props: { posts: { props: { posts } } } }

    export async  function userGetPosts (){
      const res = await fetch(`https://jsonplaceholder.typicode.com/posts`);
      const posts = await res.text();
      return posts;
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search