I have the following where I am able to print the data coming from getServerSideProps.
But when I pass it on to the component section, the prop value posts is undefined. Why?
The following is under /pages and is inside the base index.tsx file.
import type { NextPage } from 'next'
import Post from '../components/Post'
const Home: NextPage = ({ posts }) => {
// This prints undefined. This is the issue.
console.log(posts)
return (
<div>
<Post posts={posts}/>
</div>
)
}
export default Home
export const getServerSideProps = async () => {
const response = await fetch('http://localhost:8080/posts/all')
const data = await response.json()
// this prints correctly
console.log(data)
return {
props: {
posts: data
}
}
};
Updates to show _app.tsx file
import Home from '../pages';
const TestApp = () => {
return <>
<Home />
</>
}
export default TestApp
Remove the custom _app.tsx file or update it to accept a Component prop and render it as shown in the Nextjs documentation for a Custom App.
The problem is this custom App is always rendering the Home component (with no props) so it's printing undefined. Then, try navigating to / on localhost. It should render the index.tsx file and properly invoke getServerSideProps and pass the result to the component as you expect.