GetServerSideProps not getting called for nested page in Next with Typescript - reactjs

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
}
}
}

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"

Related

Why does react-query query not work when parameter from router.query returns undefined on refresh?

When page is refreshed query is lost, disappears from react-query-devtools.
Before Next.js, I was using a react and react-router where I would pull a parameter from the router like this:
const { id } = useParams();
It worked then. With the help of the, Next.js Routing documentation
I have replaced useParams with:
import { usePZDetailData } from "../../hooks/usePZData";
import { useRouter } from "next/router";
const PZDetail = () => {
const router = useRouter();
const { id } = router.query;
const { } = usePZDetailData(id);
return <></>;
};
export default PZDetail;
Does not work on refresh. I found a similar topic, but manually using 'refetch' from react-query in useEffects doesn't seem like a good solution. How to do it then?
Edit
Referring to the comment, I am enclosing the rest of the code, the react-query hook. Together with the one already placed above, it forms a whole.
const fetchPZDetailData = (id) => {
return axiosInstance.get(`documents/pzs/${id}`);
};
export const usePZDetailData = (id) => {
return useQuery(["pzs", id], () => fetchPZDetailData(id), {});
};
Edit 2
I attach PZList page code with <Link> implementation
import Link from "next/link";
import React from "react";
import TableModel from "../../components/TableModel";
import { usePZSData } from "../../hooks/usePZData";
import { createColumnHelper } from "#tanstack/react-table";
type PZProps = {
id: number;
title: string;
entry_into_storage_date: string;
};
const index = () => {
const { data: PZS, isLoading } = usePZSData();
const columnHelper = createColumnHelper<PZProps>();
const columns = [
columnHelper.accessor("title", {
cell: (info) => (
<span>
<Link
href={`/pzs/${info.row.original.id}`}
>{`Dokument ${info.row.original.id}`}</Link>
</span>
),
header: "Tytuł",
}),
columnHelper.accessor("entry_into_storage_date", {
header: "Data wprowadzenia na stan ",
}),
];
return (
<div>
{isLoading ? (
"loading "
) : (
<TableModel data={PZS?.data} columns={columns} />
)}
</div>
);
};
export default index;
What you're experiencing is due to the Next.js' Automatic Static Optimization.
If getServerSideProps or getInitialProps is present in a page, Next.js
will switch to render the page on-demand, per-request (meaning
Server-Side Rendering).
If the above is not the case, Next.js will statically optimize your
page automatically by prerendering the page to static HTML.
During prerendering, the router's query object will be empty since we
do not have query information to provide during this phase. After
hydration, Next.js will trigger an update to your application to
provide the route parameters in the query object.
Since your page doesn't have getServerSideProps or getInitialProps, Next.js statically optimizes it automatically by prerendering it to static HTML. During this process the query string is an empty object, meaning in the first render router.query.id will be undefined. The query string value is only updated after hydration, triggering another render.
In your case, you can work around this by disabling the query if id is undefined. You can do so by passing the enabled option to the useQuery call.
export const usePZDetailData = (id) => {
return useQuery(["pzs", id], () => fetchPZDetailData(id), {
enabled: id
});
};
This will prevent making the request to the API if id is not defined during first render, and will make the request once its value is known after hydration.

getServerSideProps() not running using component

I'm making a small web app with Next.js and I'm not sure why, but getServerSideProps() isn't running when I use the component. I previously had the following code on a page in /pages, but I moved it to use as a component.
export const getServerSideProps = async () => {
console.log("in getServerSideProps") // never shows
let bans = await fetch('http://localhost:3000/api/get_bans').then((res) => {
return res.json();
})
return {
props: { bans: bans }
}
}
const BansList = (listName, bans) => {
bans = bans.bans
console.log(bans) // undefined
return (
<h1>test</h1>
)
}
I've stripped the code down to easily show what's wrong. When I use that as a component getServerSideProps isn't run, so bans is always undefined.
getServserSideProps only works on page-level, not component level. You have to use a page component under pages/
More info here: https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering

Error: getStaticPaths is required for dynamic SSG pages and is missing for "xxx". NextJS

I am getting this error "Error: getStaticPaths is required for dynamic SSG pages and is missing for 'xxx'" when I try to create my page in NextJS.
I don't want to generate any static page on build time. So why do I need to create a 'getStaticPaths' function?
If you are creating a dynamic page eg: product/[slug].tsx then even if you don't want to create any page on build time you need to create a getStaticPaths method to set the fallback property and let NextJS know what to do when the page you are trying to get doesn't exist.
export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {
return {
paths: [], //indicates that no page needs be created at build time
fallback: 'blocking' //indicates the type of fallback
}
}
getStaticPaths does mainly two things:
Indicate which paths should be created on build time (returning a paths array)
Indicate what to do when a certain page eg: "product/myProduct123" doesn't exist in the NextJS Cache (returning a fallback type)
Dynamic Routing Next Js
pages/users/[id].js
import React from 'react'
const User = ({ user }) => {
return (
<div className="row">
<div className="col-md-6 offset-md-3">
<div className="card">
<div className="card-body text-center">
<h3>{user.name}</h3>
<p>Email: {user.email} </p>
</div>
</div>
</div>
</div>
)
}
export async function getStaticPaths() {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const users = await res.json()
const paths = users.map((user) => ({
params: { id: user.id.toString() },
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${params.id}`)
const user = await res.json()
return { props: { user } }
}
export default User
For rendering dynamic route use getServerSideProps() instead of getStaticProps()
For Example:
export async function getServerSideProps({
locale,
}: GetServerSidePropsContext): Promise<GetServerSidePropsResult<Record<string, unknown>>> {
return {
props: {
...(await serverSideTranslations(locale || 'de', ['common', 'employees'], nextI18nextConfig)),
},
}
}
You can check here as well
if you are using getStaticPaths, you are telling next.js that you want to pregenerate that page. However since you used it inside a dynamic page, next.js does not know in advance how many pages it has to create.
with getStaticPaths, we fetch the database. If we are rendering blogs, we fetch the database to decide how many blogs we have, what would be idOfBlogPost and then based on this information, getStaticPath will pre-generate pages.
also, getStaticProps does not run only during the build time. If you add revalidate:numberOfSeconds, next.js will recreate new page with fresh data after "numberOfSeconds" time.
You're rendering a dynamic route so use getServerSideProps() instead of getStaticProps()

where to use getInitialProps when auto-direct from one page to another

In my application I am auto-directing from '/' to '/PageOne' like this:
const Home = () => {
const router = useRouter();
useEffect(() => {
router.push('/pageone', undefined, { shallow: true });
}, []);
return <PageOne />;
};
and in my PageOne, I want to use getInitialProps like:
const pageOne = (data) => {
return (
<Layout>
...
</Layout>
);
};
pageOne.getInitialProps = async (
ctx: NextPageContext
): Promise<{ data }> => {
const response = await someAPICall()
return {
data: response.data
};
};
export default pageOne;
This will cause an error in my Home page because I referenced to PageOne using and it is missing the param "data", but I'm not able to pass the data to because the data are not there when rendering Home page.
Shall I call the API to get data in Home page instead of PageOne? If I do so, will refreshing PageOne leads to another API call to get most recent data or the API will be called only when refreshing Home page?
Do not use shallow routing because that is meant to just change the url - a good use case is adding a query string or indicating to the application that something has changed when its bookmarked, e.g: ?chat=true (not your usecase)
Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps.
It's one of the caveats called out in this page => https://nextjs.org/docs/routing/shallow-routing#caveats
If not already, you would benefit from starting to use global state in your application
https://github.com/vercel/next.js/tree/canary/examples/with-redux
or you can use in-built features:
https://www.basefactor.com/global-state-with-react

Fetching Data from API using NextJS and Material UI React

I am trying to create dynamic pages that shows individual book details (i.e. title/author etc) on a separate page based on a query string of the "id" of each book. However, I am having difficulty in understanding how to make a request to a API endpoint using NextJS that will get the book details based on its "id". I would like to use Material UI as a UI Framework.
ISSUE: When I run npm run dev the book page loads but the book's "props" are not being passed along to the BookAttributes component. The console.log(book) I added in the book page is undefined and the console.log(title) in BookAttributes is undefined as well.
I've tested the API endpoint in POSTMAN and it appears to work.
When I refactor the same code using Semantic UI-React instead of Material UI, the book pages load correctly.
I am using the NextJS Material UI starter template from the Material UI website as a baseline.
I am fairly new to NextJS and Material UI so your assistance and guidance would be greatly appreciated. Thank you for your help on this!
Here is the code I have so. I have tried to keep in clean and simple.
BOOK PAGE (within 'pages' directory)
import axios from 'axios';
import BookAttributes from '../components/Book/BookAttributes';
function Book({ book }) {
console.log(book)
return (
<>
<h1>Book Page</h1>
<BookAttributes {...book} />
</>
)
}
Book.getInitalProps = async ({ query: { _id } }) => {
const url = 'http://localhost:3000/api/book';
const payload = { params: { _id }}
const response = await axios.get(url, payload)
return { book: response.data }
}
export default Book;
BOOK API ENDPOINT (within 'pages/api' directory)
import Book from '../../models/Book';
import connectDb from '../../utils/connectDb';
connectDb()
export default async (req, res) => {
const { _id } = req.query
const book = await Book.findOne({ _id })
res.status(200).json(book);
}
BOOK ATTRIBUTE COMPONENT (within 'components' directory)
import React from 'react';
function BookAttributes({ title }) {
console.log(title)
return (
<>
<h1>{title}</h1>
</>
)
}
export default BookAttributes;
You should be using dynamic routes here if you want to work with data-fetching methods like getStaticProps or getServerSideProps.
You can create a page like pages/book/[id].js. But to generate the page you have to decide what data-fetching method you want to run. If the data for the page doesn't change very often you can choose to use static-site-generation using getStaticProps which will generate the pages at build time. If the data will be changing a lot you can either do server-side-rendering using getServerSideProps or fetch the data client-side.
Here is an example for your use-case that you can use for server-side-rendering using getServerSideProps, keep in mind the API call inside getServerSideProps might fail so you should have appropriate error handling.
In pages/book/[id].js
import axios from 'axios';
import BookAttributes from '../components/Book/BookAttributes';
export const getServerSideProps = async (ctx) => {
const bookId = ctx.params?.id
const url = 'http://localhost:3000/api/book';
const response = await axios.get(url, { params: { _id: bookId} })
return {
props: {
book: response.data
}
}
}
function Book({ book }) {
return (
<>
<h1>Book Page</h1>
<BookAttributes {...book} />
</>
)
}
export default Book;
Using static-site-generation
Because the page is dynamic you have to provide a list of paths for which nextjs will generate the pages. You can do that by exporting an async function called getStaticPaths.
in pages/book/[id].js
import axios from 'axios';
import BookAttributes from '../components/Book/BookAttributes';
export const getStaticPaths = async () => {
// here you have two options if you know all the ids of the books
// you can fetch that data from the api and use all the ids to generate
// a list of paths or show a fallback version of page if you don't know all
// ids and still want the page to be static
// Pseudo code might look like this
const res = await axios.get('api-endpoint-to-fetch-all-the-books')
const paths = res.data.map(book => ({ params: { id: book.id }}))
return {
paths,
fallback: false
}
}
export const getStaticProps = async (ctx) => {
const bookId = ctx.params?.id
const url = 'http://localhost:3000/api/book';
const response = await axios.get(url, { params: { _id: bookId} })
return {
props: {
book: response.data
}
}
}
function Book({ book }) {
return (
<>
<h1>Book Page</h1>
<BookAttributes {...book} />
</>
)
}
export default Book;
The fallback property in the returned value of getStaticPaths is somewhat important to understand. If you know all the necessary id for the pages you can set the fallback to false. In this case nextjs will simply show a 404 error page for all the paths that were not returned from the function getStaticPaths.
If fallback is set to true nextjs will show a fallback version of page instead of a 404 page for the paths that were not returned from the getStaticPaths function. Now where should you set fallback to true? Let's suppose in your case new books are added to the database frequently, but the data for the books doesn't change very often so you want the pages to be static. In this case, you can set fallback to true and generate a list of paths based on avaliable book ids. For the new books nextjs will first show the fallback version of the page than fetch the data based on the id provided in the request and will send the data as JSON which will be used to render the page in the client.

Resources