Learn how to pass an id from the query parameters to the getInitialProps function in Next.js

Looking to create a basic website that displays content from a database? Utilizing the getInitialProps function from Next.js documentation can help with server-side rendering: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialprops-for-older-versions-of-nextjs

Currently, things are functioning smoothly, but now I want to enhance the functionality by enabling access to specific articles based on their ID. The desired URL structure is as follows:

http://localhost:3000/articles/<some_id>

I've managed to set this up, but the next step involves extracting the ID from the query parameter and passing it to the getInitialProps function in order to fetch only that particular article from the API. The challenge lies in figuring out how to pass down the router props for accessing the ID and making the API call.

import { withRouter } from "next/router";
import fetch from "isomorphic-unfetch";

const Article = ({ router }) => {
  console.log(router);
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
};

Article.getInitialProps = async props => {
  console.log(props);
  const res = await fetch(
    `https://admin.jozefrzadkosz-portfolio.pl/articles/${router.query.id}`
  );
  const articles = await res.json();
  return { articles };
};

export default withRouter(Article);

Answer №1

The function getInitialProps receives an context object as an argument, which contains the property query.

Make sure to retrieve your desired value from this object.

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

Discord.js: Merging strings while pushing to an array

I am currently updating an embed message to notify users who have "enlisted" in a list by reacting. However, I am encountering an issue where the strings from the entire array are getting combined when the length of the array reaches 2 before adding a new ...

Dealing with Oversized Images in Jcrop: Tips and Tricks

Utilizing Jcrop for cropping images, everything runs smoothly with small images. However, when I attempt to use large images like 2080x2080 or 1600x1600, it takes up the entire screen and cannot be controlled by CSS properties such as width and height in t ...

Dismiss the Popover in Ionic 2

After opening a popover that redirects me to another page and then returning to the root page (popToRoot), I reload the data/dom upon an event and dismiss the popup once the json data is received from the server. Everything works smoothly with a lengthy ti ...

Nextjs application routers offer dynamic routing functionality and the ability to generate metadata

Struggling with static site generation while building a blog site in nextjs with app router? If you've read through Next.js official documentation and still need assistance, check out my project structure pictured https://i.stack.imgur.com/ZOYkf.png. ...

Tips for successfully passing an empty value as a prop on a Material UI button

Currently, I am utilizing a ternary operator in a prop for a button. It is functioning as expected, but a warning regarding the empty string keeps appearing in the browser. I am looking for an alternative solution to avoid this error. <Button varia ...

What could be causing the issue with React Router not functioning properly in Material UI?

I'm currently working on creating a tab and adding routing inside the first tab. However, I am facing an issue where the desired page does not display after clicking on the link. Strangely, upon refreshing the page, the corresponding page appears as e ...

What strategies can be used to efficiently perform Asynchronous Operations on a high volume of rows in a particular database table?

I am looking to perform Asynchronous Operations on every row of a specific database table, which could potentially contain 500,000, 600,000, or even more rows. My initial approach was: router.get('/users', async (req, res) => { const users = ...

Angular UI Grid failing to properly display date formatting

Currently, I am using Angular's UI Grid to showcase multiple columns. However, I am facing an issue with formatting the date column. The date is being displayed as /Date(1451346632162-0000)/, and similar formats. I have attempted to apply filters in ...

I successfully coded a function without utilizing the function key, but unfortunately I am encountering difficulties when trying to output the

I have created a function without using the function keyword. The function should take the age above 15 and push it into an array. I have been able to do that, but I am struggling to print the result. Can anyone help me with this? my code <script> ...

Module '@tanstack/react-table' cannot be located even though it has been successfully installed

Currently, I am tackling a TypeScript React project and encountering an issue while attempting to import ColumnDef from @tanstack/react-table in my columns.tsx file. import { ColumnDef } from "@tanstack/react-table"; export type Payment = { id ...

Node receiving empty array as result after processing post request

My current task involves testing the post method on Postman. Strangely, every time I post the result it shows an empty array []. Upon further investigation by console logging on the node side, it also returns an empty array. CREATE TABLE users ( user_ ...

Verifying if checkboxes are selected in PHP using JavaScript

echo '<div class="col-lg-10 col-lg-offset-1 panel">' . "<table id='data' class='table'> <tr> <th></th> <th>Document No</th> <th>AWB NO</th> ...

What are the steps for updating an NPM package that was installed from a Git repository?

I'm struggling to understand how to update a package that was installed from a git repository. Let's say I have a package located at git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b3bda094b3bda0b8b5b6fab1 ...

Grabbing a section of a URL through a bookmarklet: A simple guide

Recently, I've been using this handy bookmarklet: javascript:currentUrl=document.location.href;document.location.assign(currentUrl+'embed'); This neat tool grabs the current URL, such as www.example.com/knZg_INW8fL/, and adds embed to it f ...

Unable to set value for React MUI TextField in React Hook Form Controller inside MUI Stepper Dialog

I am facing an issue with my Button that triggers a MUI Dialog to open. Within the Dialog, there is a MUI Stepper as part of my form which has different required and non-required inputs. //Sample Input <Controller name="stateName" co ...

The findByIdAndUpdate() function lacks the ability to modify the collection

I'm encountering an issue when trying to update a product using mongodb and redux. It seems that the database is not reflecting the changes after I attempt to update the product. Can someone please assist me with this problem? Here is my product.js f ...

Oops! You forgot to include the necessary getStaticPaths function for dynamic SSG pages on '/blogs/[post]'

Whenever I attempt to execute npm run build, an error occurs. The following build error occurred: Error: getStaticPaths is required for dynamic SSG pages and is missing for '/blogs/[post]'. This is the code snippet causing the issue: function ...

Tips for transferring the button ID value to a GET request?

I recently developed a Node.js application that interacts with a database containing student information and their current marks. Utilizing MongoDB, I retrieve the data and present it in a table within an .ejs file. index.js router.get("/dashboard", funct ...

Are these two glob patterns distinct from each other in any way?

images/**/*.{png,svg} images/**/*.+(png|svg) After running tests on both expressions, it appears that they generally yield identical outcomes. However, it is crucial to confirm that they are indeed equivalent. ...

Tips for automatically filling in fields when a button is clicked in a React application

I'm attempting to pre-fill the form fields that are duplicated with data from already filled fields. When I click the "Add Fields" button, new fields are replicated, but I want them to be pre-populated with data from existing fields. How can I access ...