What is the best way to send an Object to the page component while implementing Dynamic Routing in NextJS?

I am currently utilizing the "app" router within NextJS and aiming to implement Dynamic Routes in order to dynamically generate pages for blog posts.

The issue I'm facing involves passing an Object to the dynamically created page, specifically a Post object with attributes like

{id: number, title: string, likes: number}
. It seems that achieving this is not straightforward.

In the best-case scenario, if I have a route as /posts/[id], such as /posts/1, then I can retrieve the value 1 inside the dynamically generated page by defining the type:

interface PostPageProps {
  params: {
    id: string;
  };
}

and using it as follows:

export default async function PostPage({ params }: PostPageProps) {
    // ...
    // params.id can be accessed.
}

Nevertheless, it appears impossible to capture an entire custom Object, like a Post object, on the dynamically created page.


Directory Layout

/app
  - /components
  - /posts
    - /[id]
      - page.tsx
    - page.tsx
  - favicon.ico
  - globals.css
  - layout.tsx
  - page.tsx

./app/posts/page.tsx

"use client";

// ...

type Post = {
  id: number;
  title: string;
  likes: number;
};

export default function Page() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchPosts() {
      ...
    }

    fetchPosts();
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>{error}</p>;

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <h1 className="text-3xl font-bold underline">
        {posts.map((post) => (
          <li key={post.id}>
            <Link href={`/posts/${post.id}`} className="block">
              {post.title}
            </Link>
          </li>
        ))}
      </h1>
    </main>
  );
}

./app/posts/[id]/page.tsx

type Post = {
  id: number;
  title: string;
  likes: number;
};

interface PostPageProps {
  params: {
    id: string;
  };
}

export default async function PostPage({ params }: PostPageProps) {
  const { id } = params;
  console.warn(params);
  return (
    <div>
      <h1>{id}</h1>
    </div>
  );
}

One potential method to access a specific page involves utilizing the id provided in PostPageProps to filter out the particular post of interest after fetching the data (stored in a .json file in /public). However, this approach would require loading the entire json file and filtering it for a specific post each time a specific post page is accessed. This could impact performance negatively, prompting my exploration of loading all data at once in the "parent" page from which I can navigate to each post on the dynamically created page (route). This is the recommended approach when utilizing the App router in NextJS, note that this substitutes the use of getStaticProps which isn't applicable in my scenario.

If there exists a more effective approach to tackle this, please share your insights.

Answer №1

It is not possible to directly send an object as props through a link.

One way around this limitation is to pass the object properties as query parameters in the URL and then extract them using searchParams, although this method is not recommended.

A more efficient solution would be to utilize generateStaticParams to pre-generate each page during the build process.

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

What is preventing the console from displaying [Object] instead of my information?

Looking to add a meme command to my Discord bot using data stored in a JSON file called memes.json. In my index.js file, I have a variable set up to retrieve the data as follows: const meme = require("./memes.json"). However, when trying to embed the meme ...

Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly. <template> <div id="index"> <img :src="image.src" v-for="image in image ...

Creating an aperture in a form using a different shape in THREE.js

Currently, I am utilizing the D3-threeD2.js library to convert SVG files into THREE.Shape(s) that can be extruded with three.js. The process works smoothly, however, when it comes to incorporating holes, I encounter an issue. Imagine a shape resembling a ...

Deciphering the hidden power of anonymous functions within Express.js

Recently, I started learning about express and am grappling with understanding callbacks in RESTful actions. In the following PUT request code snippet, I am puzzled by the specific line that is highlighted below. Why is response.pageInfo.book being assigne ...

What is the reason behind HTML IDs being displayed as global variables in a web browser?

Browser exposes HTML IDs as global variables. <span id="someid" class="clsname1 clsname2 clsname3"></span> If you have the above HTML snippet, you can access a global variable called someid. You can interact with it in your console like this: ...

Ensure the ng-change event triggers only when the user finishes typing

In the process of creating a search feature for my angularjs web application, I am currently facing an issue where a request is sent to the backend server every time a user types something into the search field using ng-change. This results in an excessive ...

Preventing data duplication when refreshing a webpage using Node.js

I am currently utilizing Mustache and Nodejs to populate a dropdown menu with a list of options on my website. However, every time the page is refreshed, I encounter duplicate entries in the dropdown. How can this issue be resolved? I trust that my inquiry ...

What is the process for transferring a file to a server from a PhoneGap or web application using FTP?

Can a PhoneGap application establish a connection with a server and transfer files using FTP? In simpler terms, is it feasible to initiate an FTP connection using Ajax or jQuery? ...

Extracting data from a JSON file with the help of Node.js

I've recently delved into node.js and find myself in a bit of a pickle. I have a json file called keyValue.json that looks something like this [ { "key": "key1", "value": "value1" }, { "key": "key2", "value": "value2" } ] I ...

Modify the value of select options when the page is first loaded

I want to set up a dropdown menu with a list of regions, and I need the drop down to automatically select an option based on the variable value that I assign. Here is the code snippet. <select name="_sft_location[]" class="sf-input-select" title=""&g ...

Guide on serving static HTML files using vanilla JavaScript and incorporating submodules

Is it possible to serve a static html file with elements defined in a javascript file using imports from submodules using vanilla JS? Or do I need bundling tools and/or other frameworks for this task? Here's an example code structure to showcase what ...

Restore original scale ratio to 1:1 following zoom

I am looking for a way to revert the image back to its original zoom level when a button is clicked using the onclick() event. I require the specific code for the onclick() event function. This is the div element in my HTML: div id="zoom"> ...

Encountering a hiccup during the installation process of Angular CLI

I'm encountering an issue in the command line, seeking assistance C:\Users\admin>npm -v 6.9.0 C:\Users\admin>npm install -g @angular/cli npm ERR! Unexpected end of JSON input while parsing near '...vkit/core":"8.0.4", ...

What is the significance of using parentheses around a function in JavaScript?

Currently, I am developing an application using Java and JavaScript, and while reviewing some code today, I came across a segment that seemed confusing to me. var myVariable = (function(configObj){ var width = configObj.width; var height = config ...

I need to implement a div-based dropdown with a scrollbar in JavaScript and CSS to prevent it from extending beyond the screen. Additionally, the use of struts is essential in this implementation

Dealing with a dynamically populated div-based dropdown can be tricky, especially when it extends beyond the screen's limits and hides entries. This is an inherited application that lacks support, leaving me to handle it without the necessary expertis ...

What is the best way to create a slideshow that automatically starts upon loading and pauses when hovered over?

I have recently set up a div element for my slideshow. I've included a script to enable navigation using next and previous arrows. However, I am looking to add an automatic slideshow feature that stops on hover. As a beginner, I would appreciate any a ...

Ways to verify if a firebase timestamp surpasses the present date

Would you help me with comparing a timestamp field with the current date using JavaScript? This is what I have tried so far: // Initialize an empty array to store documents let myDocs = []; // Call the getDocs function and handle the response await getDo ...

Creating multiple conditions in AngularJS for a specified number and text value in JavaScript is essential for ensuring accurate

Apologies for the perhaps silly question and my imperfect English. I am new to programming, and I have a query regarding a counter button. When I press the button, the number increases by 1. However, once it reaches a value of 34, how can I implement a con ...

Finding the largest number that is less than a specified variable within an array

I have a JavaScript array and a variable, set up like this; var values = [0, 1200, 3260, 9430, 13220], targetValue = 4500; How can I efficiently find the largest value in the array that is less than or equal to the given variable? In the provided ex ...

The Sequelize findOne method fails to return the desired results, resulting in an empty

My findOne function with include is not working as expected. It is not returning any data. I am missing data for Deal, which is related to Redemption [] <- I should have data here. Deal.belongsTo(models.Redemption, { foreignKey: 'redemptionI ...