Obtain a pair of values from the getStaticPaths function

Currently, I'm utilizing getStaticPaths method to establish a product page in NextJS framework. My products are retrieved from wooCommerce; however, there's an issue:

I intend to utilize "permalink" for the URL of my NextJS route, but at the same time, I require the product ID to fetch data related to that specific product being displayed.

The structure of my code is somewhat similar to this:

export async function getStaticPaths() {
    const res = await fetch('https://.../products/')
    const products = await res.json()
    const paths = products.map((product) => ({
      params: { permalink: product.slug, id: product.id},
    }))
    return { paths, fallback: false }
  }
  

  export async function getStaticProps({params}) {
    console.log(params);
    const res = await fetch(`https://.../products/${params.id}`)
    const productsData = await res.json()
  
    return { props: { productsData } }
  }

I am attempting to transfer the ID through params, yet NextJS only anticipates variables present in the JavaScript filename (in this scenario, [permalink].js); hence, the ID is not transferred to getStaticProps, and I necessitate the ID to retrieve product data as the API does not cooperate with permalinks.

Is there a potential way to transmit another variable (such as ID in this context) from getStaticPaths to getStaticProps?

Answer №1

async function retrieveStaticPaths() {
   const response = await fetch('https://.../items/')
   const items = await response.json()
   let pathsArray = []
    
   for (const item of items){
      pathsArray.push({params: {link: item.slug }, identifier: item.unique_id})

   }
   return { pathsArray, enableFallback: false }
}

Answer №2

To properly set up your routing, you'll have to generate a nested dynamic route in the following format: page/[permalink]/[id].js

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

Creating a dynamic side navigation menu that adjusts to different screen sizes

I have been working on a project's webpage that was initially created by another Software Engineer. After he left, I continued to work on the webpage. The issue I encountered is that he preferred a side menu over a navbar using the left-panel and righ ...

Searching for the search parameter in the Wordpress admin-ajax.php file. What could it

Just diving into the world of php and wordpress. Are there any search parameters I can include in admin-ajax.php? Here are the parameters in the ajax post; action: rblivep data[uuid]: uid_search_0 data[name]: grid_small_1 data[posts_per_page]: 8 data[pagin ...

Safari has trouble with AJAX cross-origin requests, while Chrome and Firefox handle them without issue

I am developing a Shopify app that utilizes script tags and requires an ajax call to our server to retrieve necessary information about the shop. While everything seemed to be functioning correctly, my colleague pointed out that it was not working on his i ...

Keep the user on the current page even after submitting the parameter

I have a situation where I am loading a page into a specific div. This loaded page contains a link that includes a parameter which directs to another page for deletion. However, when I click on the loaded page within the div, it redirects me to the deletio ...

Prevent removal of h2 tag within a contenteditable segment

Can a section be made permanent within a contenteditable element to prevent user removal? I have an h2 tag inside a contentEditable div. I do not want the user to be able to edit the h2 tag, so I set contentEditable=false, but they can still select and de ...

The error in Node.js states: "Type error: Cannot access property 'auth_token' of an undefined variable."

Greetings, I am encountering a TypeError when attempting to redirect to my welcome page. The issue seems to be occurring in the verifyToken.js file when trying to access the value of req.cookies.auth_token. Furthermore, I have included the index.js code f ...

The error message "Unconfigured error" continues to appear when using Next.js Image

www.gravatar.com is not being properly configured under images in your `next.config.js` file. This is my current configuration: const config = { reactStrictMode: true, images: { domains: ["gravatar.com"], disableStaticImages: true, }, } mod ...

Control three.js camera rotation based on the movement of a mobile device within a specified div element

Is there a way to incorporate mobile device movement control for camera rotation in this demo along with the current mouse movement control? The camera rotation has been set up for mobile here, but not in conjunction with mouse movement. The following code ...

Working with jQuery: Creating multiple lightboxes using the same jQuery code

Is there a way to create a universal lightbox with the same code for all lightbox functions on the page using JQuery? $(document).ready(function() { $('.lightbox').click(function() { $('.backdrop, .box').animat ...

Calculate the total count of responses within the JSON data returned

Hello all, I need some guidance on calculating the total number of responses in a JSON response that adhere to a specific rule using JavaScript. Here is the JSON response that I am discussing: [ { "InvoiceNumber":"INV0319", "InvoiceOrd ...

What are the best strategies for eliminating element cloning and duplication in Vue?

As a novice programmer, I've developed a web app similar to Trello. It allows users to create boards and within those boards, lists can be created. Each list is displayed uniquely with different IDs. However, the list items are displayed with the same ...

Ability to access functions from required modules that are defined within the calling module

Is there a way to call a function within a required module that is defined in the main program without copying or creating separate files? Main.js: var http = require('http'); var aFunc = function() {return 1;} var bFunc = require('./bFunc ...

I am unable to utilize the Web Share API for sharing a file within my React app written in TypeScript

Trying to launch a WebApp for sharing files has been quite a challenge. After some thorough research, I stumbled upon the Web Share API which seemed like the perfect solution based on standard practices. The documentation provided a clear outline of how it ...

Eliminating an SVG component from the webpage with the help of jQuery

Utilizing jQuery to insert an element into an embedded SVG can be achieved with the following code: var rect = SVG('rect'); $(rect).attr( { x: left, y: top, width: right - lef ...

Tips for effectively passing "this" to direct the event initiator in react js?

I'm facing an issue where I am attempting to send a buttons object to a function and then access its properties within that function. Here's my button : <RaisedButton label="Primary" id = "1" onTouchTap={()=>this.buttonPress(this)} prima ...

Utilizing jQuery to fetch the source value of an image when the closest radio button is selected

On my website, I have a collection of divs that display color swatches in thumbnail size images. What I want to achieve is updating the main product image when a user clicks on a radio button by fetching the source value of the image inside the label eleme ...

Exploring the Power of D3.js: Loading and Visualizing Multiple Networks using JSON Files and the Force

I have a collection of networks consisting of nodes and links stored in various JSON files. I am using D3.js to load them into a Force Layout, where they each load and layout perfectly when loaded individually. However, I would like to enhance the function ...

Having trouble with the toggle button on the Bootstrap 5 navbar?

I am facing an issue with my HTML code where the toggle button does not display properly when I resize the browser screen. Upon clicking on it, the navigation bar items do not show at all. Here is a screenshot of my website <html> <head> ...

Passing attributes to a pre-loaded component with next/link

import TestAcademy from './test-academy.js'; function MyApp({ Component, pageProps }) { const router = useRouter() const [approved, setApproved] = useState(false) ... return( <Link href='/test-academy' ...

Steps for setting up and shutting down the server during integration testing with Express and Supertest on NodeJS

One issue that continues to plague me is the "Address already in use::3000" error which pops up whenever I run my tests. This is what I currently have set up: package.json "scripts": { "test": "jest --watchAll --verbose --runInBand --maxWorkers=1" ...