Currently working with NextJS 13
and executing the following operations within the app
directory.
I am attempting to utilize the generateStaticParams
function to generate static pages during build time.
The route structure is: subpage/[categoryName]/[gifId]
Hence, here are some example routes:
/subpage/fashion/1
/subpage/fashion/2
/subpage/fashion/3
/subpage/technology/1
/subpage/technology/2
/subpage/technology/3
/subpage/technology/4
... and so forth.
The route subpage/[categoryName]
will not have any content and may display an error or redirect elsewhere.
The complete path subpage/[categoryName]/[gifId]
including the [gifId]
segment is mandatory.
I require making REST requests to fetch data for these pages.
How can I set this up in my page.tsx
file located at:
subpage/[categoryName]/[gifId]/page.tsx
?
If it were a single dynamic path, it would be simple. Please refer to my implementation below for that scenario.
However, due to the nesting of 2 dynamic paths [categoryName]
and [gifId]
, I am a bit confused on how to proceed. Kindly provide guidance.
import MyComponent from "../../../components/MyComponent";
import { PartialGifProps, TagType} from "../../../utils/typings";
import axios from "axios";
import {apiDomain, defaultHeaders} from "../../../utils/constants";
const perPage = 40;
type Props = {
params: {
gifId: string,
},
}
export const generateStaticParams = async () => {
const url = `${apiDomain}/get_gif_count`; // Will adjust backend if need to include category.
const fetchGifs = await axios.get(url, { headers: defaultHeaders });
const { total_count: totalCount } : TagType = fetchGifs.data;
const totalPages = Math.ceil(totalCount / perPage);
let paramsList = [];
for (let i = 1; i <= totalPages; i++) {
paramsList.push({ gifId: i.toString() })
}
// Sample output of paramsList:
// [
// { gifId: '1', },
// { gifId: '2', },
// { gifId: '3', },
// .......
// ]
return paramsList;
}
const MyPage = async ({params: {gifId}}: Props) => {
const url = `${apiDomain}/get_partial?page=${gifId}&per_page=${perPage}`;
const fetchGifs = await axios.get(url, { headers: defaultHeaders });
const { gifs } : PartialGifProps = fetchGifs.data;
return (
<div className='text-white'>
<MyComponent gifs={gifs}/>
</div>
);
};
export default MyPage;