Issue
I have a page set up at /article/[id] that is supposed to fetch an article for the id using getServerSideProps. It seems that getServerSideProps is not getting called at all since I don't see any of the console logs.
When I navigate to the page, it says "TypeError: Cannot read properties of undefined (reading 'title')" since article is undefined. When I replace the page content with simple static text, it shows up fine with the right url.
The file is currently called [id].tsx, but I tried different names with the same result.
import { GetServerSideProps, NextPage } from 'next'
import Link from 'next/link'
interface Article {
userId: number;
id: number;
title: string;
body: string;
}
interface ArticleProps {
article: Article
}
const ArticleDetail: NextPage<ArticleProps> = ({ article }) => {
return (
// <p>Hello</p> // Shows up on the page
<div>
<h1>{article.title}</h1>
<p>{article.body}</p>
<br />
<Link href="/">Go Back</Link>
</div>
)
}
export default ArticleDetail
export const getServersideProps: GetServerSideProps = async (context) => {
console.log("hello"); // this is never logged
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${context.params?.id}`)
const article = await res.json() as Article
console.log(article); // this is never logged
return {
props: {
article
}
}
}
Solution
Move your getServerSideProps
(beware of the case sensitivity) to your page component in the /pages folder and then pass it down thru props. You can not use it in your nested React components
EDIT after your response: the issue is that your getServerSideProps
never gets called because of your typo "getServersideProps
"
Answered By - brothy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.