Experimenting with nested dual dynamic routing within the app's directory

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;

Answer №1

To retrieve the categoryName, you can follow the same process as obtaining the gifId. This involves utilizing the params prop

type Props = {
  params: {
    gifId: string,
    categoryName: string,
  },
}

const MyPage = async ({params: {gifId, categoryName}}: Props) => {
  console.log('categoryName =', categoryName);

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing tests for an asynchronous function

I recently encountered a bug in my AWS Lambda code written in NodeJS 6.10 that caused me two sleepless nights. I didn't conduct integration testing, relying solely on unit tests, which led to the oversight. After inserting return workerCallback(err);, ...

Error message: Upon refreshing the page, the React Router is unable to read properties of

While developing a recipe application using the Edamam recipe API, everything was functioning smoothly until an issue arose when refreshing the Recipe Detail page. The error occurs specifically when trying to refresh the page with a URL like http://localho ...

The elements being parsed are appearing as undefined

Currently, I am attempting to analyze this JSON structure: { "customers": [ { "name":"joe" , "cars":[ {"name":"honda","visits":[ {"date":"01/30/14","Id":"201"}, {"date":"01/30/14","Id":"201"}, {"date":"02/12/14","Id":"109"} ...

How can I add text to an HTML5 SVG similar to using the HTML5 <p> tag?

I am currently working on creating dynamic rectangular boxes and I am facing some difficulties with inserting text into the shapes. The SVG text requires setting x and y coordinates in separate text tags, and doesn't have built-in width and height pro ...

Executing API calls utilizing Axios in a NodeJS environment with the Authorization Basic feature

I have developed an API to retrieve a token from PayPal. curl -v POST https://api.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: application/json" \ -H "Accept-Language: en_US" \ -u "CLIENT_ID:SECRET" &b ...

"Encountered CLIENT_FETCH_ERROR while attempting to log in with NextAuth.js, despite providing the NEXTAUTH

I am currently working on setting up credentials authentication with NextAuth.js in collaboration with Strapi for backend development and Next.js for frontend. However, when attempting to log in a user using the signIn function, I encounter the following e ...

What is the best way for me to grasp the concept and functionality of 'Array.prototype.join'?

When I tried using Array.prototype.join on a multidimensional array, I encountered a surprising result. To investigate further, I looked into the inner workings of Array.prototype.join and found it to be native code. [1,2,3,4,5,6,7,8].join('') [ ...

ReactJS: error occurs when trying to fetch data and encountering issues with reading properties

I am currently attempting to initiate an API call (a GET request) in order to download a document. However, I am encountering an error when making the API call: TypeError: Cannot read properties of undefined (reading 'payload') const printPin ...

Display data from a PHP array in a JavaScript alert box

Within my Wordpress registration form, I am attempting to display the $error array in an alert message. I have experimented with using console.log(), but it does not show any output. Even when using JSON.stringify(), the alert only displays the word: true ...

Refreshing the Table to Update Data

I am working on a jquery application that includes a table with time and number fields. My goal is to increment the values every 3 seconds by creating a function to update the numbers automatically. Initially, the data in the table looks like this: Kobe ...

What is the prescribed interface or datatype for symbol type in TypeScript with JavaScript?

I have a set of symbol values in JavaScript that I want to convert to TypeScript. // Defining object values in JavaScript const size = { Large: Symbol('large'), Medium: Symbol('medium') } What is the most efficient method to conv ...

Using Node.JS, Sequelize, and Moment.JS to format dates

Seeking help on formatting a date loaded from Sequelize in my database. I'm working on a blog and need to display the creation date of an article. Here's my route: app.get("/", (req,res) =>{ Article.findAll({ order:[ [ ...

How to pass children and additional arguments to a React/NextJS component

Currently, I am utilizing NextJS with a global PageLayout wrapper that is responsible for setting the head and creating the wrapping divs for all my pages. However, I am facing a challenge as I attempt to set a custom title tag for each page. This task req ...

Step-by-step guide to uploading files using cucumber-js

Is there a way to write a script that can successfully fill out a form and upload a file using cucumber-js, selenium, and protractor? I am encountering an issue where there is no xpath/id available to click on when trying to upload a file. How have you d ...

Display the razor page in a modal dialog box

I want to display a razor page within a modal dialog: Here is the code for the razor page: <div class="container"> <div class="title modal " tabindex="-1" id="loginModal" data-keyboard="false" data-backdrop="static"> < ...

Using Vue.js watchers can sometimes cause an endless loop

I'm working on a unique aspect ratio calculator. How can I ensure my code doesn't get stuck in an endless loop when dealing with 4 variables that are dependent on each other? To address this, I implemented 4 watchers, each monitoring a specific ...

Vite encounters issues when using PNPM because of import analysis on the `node_modules/.pnpm` package

When utilizing PNPM and Vite in a monorepo, I encountered a perplexing issue. The email addresses appearing like `<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b6a9b4a580f4eef4eef9">[email protected]</a>_@<a ...

How to apply a CSS class to the body element using Angular 2

I am working with three components in my Angular application: HomeComponent, SignInComponent, and AppComponent. The Home Page (HomeComponent) is displayed when the application is opened, and when I click the "Sign In" button, the signin page opens. I want ...

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...

Utilizing TypeScript to enhance method proxying

I'm currently in the process of converting my JavaScript project to TypeScript, but I've hit a roadblock with an unresolved TypeScript error (TS2339). Within my code base, I have a class defined like this: export const devtoolsBackgroundScriptCl ...