0

I'm building a NextJs app and for some reason I'm not getting a function from the page 'Feed.tsx' to render inside 'Index.tsx'. However when I navigate to '/feed' the function renders perfectly fine. Why is that?

Feed.tsx

import Post from "../components/Post";

function PostList({ posts }){
  return( <>
    {posts?.map((post) => {
      return(
      <div key={post.id}>
        <Post post={post}/>
      </div>
      )
    })}
  </>
  )
}
export default PostList


export async function getServerSideProps(){
  const response = await fetch('http://localhost:3000/posts/')
  if (!response.ok) {
    const message = `An error occured: ${response.statusText}`;
    window.alert(message);
    return;
  }
  const data = await response.json();
  console.log(data);
  
  return{
    props:{
      posts: data,
    },
}
}

index.tsx

import Create from "./create";
import PostList from "./feed";

const Home = () => {
return(
    <div>
        <h1 className="text-blue absolute inset-y-7 left-7 text-xl font-semibold mb-20">Home</h1>
        <Create />
        <PostList />
    </div>
);}

export default Home
juliomalves
  • 42,130
  • 20
  • 150
  • 146

1 Answers1

0

getServerSideProps() can be triggered only with pages and not with components, getServerSideProps can only be exported from a page.

If you like to create a component fetched from API data, you can create it with useSWR library.

import Post from "../components/Post";
import useSWR from 'swr'

function PostList(){
//data can be fetched only from API
const { data: posts, error: errorPosts } = useSWR('/api/posts', fetcher)

if (errorPosts ) return <div>failed to load</div>
if (!posts) return <div>loading...</div>

return( <>
    {posts?.map((post) => {
      return(
      <div key={post.id}>
        <Post post={post}/>
      </div>
      )
    })}
  </>
  )
}
export default PostList

P.S. don't forget to install npm install swr

illia chill
  • 1,652
  • 7
  • 11