Creating interactive routes and pages using Next.js and Prisma, embracing dynamic functionality

I have product information cards stored in my database, and I successfully display them on the user's page. Now, I want to add a "More Details" button on each card that will link to a new page (/pages/card/[id]). However, I'm unsure how to retrieve the card value via my API when the button is clicked.

 const res = await fetch('/api/cards/' + id, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id: id })
    })
    if (res.ok) {
        const result = await (await res).json()
        if (result.redirectUrl) {
           router.push(result.redirectUrl as string)
        }
      }
    }

API

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    const { id } = req.query
        if (req.method === 'GET') {
            if (typeof id === 'string') {
                const moreDetail= await db.sales.findUnique({
                    where: { 
                        id: id },
                })
                 res.send({ redirectUrl: '/card'+[id] }) 
            }
        }

My card schema

  id          String   @id @default(cuid())
  title       String
  description String
  active      Boolean  @default(true)

Answer №1

In my opinion, I would recommend implementing an additional API endpoint that can return an array containing all available cards or at least a list of card IDs. Following this, you can create a new page to match your specified URL format /pages/card/[id].tsx. Within this file, build your page as usual but also include the exporting of two functions:

These functions are essential for informing Next.js about available paths and how to retrieve data for them during the building process.

export async function getStaticPaths() {
  const cardIds = await fetch('/api/cards', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
    });

  return {
    paths: cardIds.map((id) => (
     {
       params: { id }
     },
    )),
    fallback: false, // setting to false will throw a 404 if none match
  };
}

This allows Next.js to generate pages for all dynamic routes based on the provided information.

export async function getStaticProps({ params: { id } }) {
  const card = await fetch(`/api/cards/${id}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
    });

  return {
    props: {
      card,
    },
  }
}

By doing this, the data corresponding to a specific card ID is fetched from the API and delivered to your component to display detailed information.

I hope this serves as a helpful starting point for your project.

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

Create a collection of functions within an array that each return promises

I have created 4 different functions that return promises. By running the "hello" function and passing each subsequent function into the next .then, you can generate a single long string output. var hello = function(str){ return Promise.resolve(str + "h ...

Using JavaScript to manage form input values in React

I am currently coding a basic application using NextJS and bulma CSS. The snippet below shows the form I am working on: const MyPage = () =>{ const [firstName, setFirstName] = useState('') const [secondName, setSecondName] = useState('&ap ...

What is the best way to arrange images in a 3 by 3 grid, beginning at position 0, using JavaScript to control navigation through button clicks?

When I click on button 1, it starts at image 1 because the counter is set to 0. Clicking on button 2 takes me to image 4 with a counter value of 3, while clicking on button 3 leads to image 7 with a counter value of 6. The process should also work in reve ...

Adjust the size of a panel in Extjs when its parent div is resized

Within my div, I have included an Extjs panel using the renderTo configuration option. Can someone please advise on how to adjust the panel size dynamically when the div is resized? Appreciate any help! Thank you. ...

implement a new directive in AngularJS that references another directive in HTML

Check out the Fiddle here Upon button click, a modal window appears. Inside this modal, there is a <template-placeholder></template-placeholder>. When the button is clicked, an if-check is performed to ensure it's the correct button. If ...

The Express.js server seems to be having trouble rendering a static JavaScript file

Currently, I am in the process of constructing a website and have implemented an express.js server to collect data submitted through a form. Prior to configuring the server, I had already developed the site using static js and css files. Once the connectio ...

Is it possible to verify the authenticity of JSON data retrieved from

I'm currently working on validating JSON input from users and came across a challenge. I've found a way to check if the text a user enters is valid JSON using a simple function, like below: function IsJsonString(str) { try { JSON.par ...

Improving Page Load Speed with HTML Caching: Strategies for Enhancing Performance when over half of the data transferred is for navigation menus

I manage a complex and expansive website that contains a significant amount of repetitive HTML elements such as the navigation menu and top ribbon. Loading a single page on my site can be resource-intensive, with up to 300KB of data required, half of whic ...

Guide on aligning a popup next to the button that activated it using CSS and JavaScript

I am currently generating a dynamic quantity of divs, each containing a button that triggers a popup when clicked. I am attempting to position the popup below the specific button that activated it, but it remains static and does not move accordingly. <d ...

Utilize Axios to send data in real-time to update any changes made to an input field in

Just wanted to write about this topic because I have a burning question. (Please note that the code in this post is just an example). I'm struggling with sending the input content of name_contact on each change without using a button. Is it even poss ...

Retrieve the id within the parentheses for each checkbox that is checked and re-check each time a checkbox is selected using Kendo UI

Working with the tricky kendo-ui has made adding selectors quite challenging; however, my current task involves simply obtaining the inner contents of the id selector upon clicking an input checkbox element. Specifically, I need to extract the text between ...

Trouble with getting Tailwind CSS animations to function properly in ReactJs/NextJs

Recently, I delved into learning Tailwind and Nextjs by following a tutorial step by step. One interesting thing I encountered was trying to implement a bounce animation on an icon when it's hovered over. Surprisingly, it worked perfectly the first ti ...

Next.js: React component has an invalid ARIA attribute `ariaHidden`. Maybe you meant to use `aria-hidden` instead?

My component definition looks like this: <HiChevronDown aria-hidden="true" className= "ml-2 h-5 w-5 ..." /> However, the console warnings are telling me that I am camelCasing it. Am I missing something obvious here? Console ...

Troubleshooting: Issues with jQuery's Class selector

Having trouble setting up an alert to trigger when a specific class anchor tag is clicked inside a div. This is what my HTML section looks like... <div id="foo"> <a class='bar' href='#'>Next</a> </div> And h ...

Having trouble persisting my login status in Selenium using Python

Has anyone experienced issues with logging into Instagram using an automate tab? Previously, I didn't have any problems, but now it seems that Instagram is not allowing users to log in through automation. An error message stating the following appears ...

Techniques for sending PHP variables to window.location using JavaScript

How can I successfully include a PHP variable in a JavaScript window.location function? The current code snippet below does not seem to be working for me. echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.&apos ...

Problem with AWS Lambda function handler failing to insert data into Athena

Trying out a sample code snippet for Amazon Athena to test data insertion, but it's not working as expected. The CloudWatch logs don't show any output after the statement execution is completed. Even when switching to a simple select statement, t ...

Determine the altered props within the componentWillReceiveProps lifecycle method

During the process of debugging React code, it is common to come across situations where componentWillReceiveProps gets triggered unexpectedly, but identifying which prop change is causing this issue can be challenging. Is there a method available to easi ...

The extjs datecolumn is displaying dates with a one-day discrepancy

My Ext.grid has a datecolumn, but I'm experiencing an issue where the dates displayed are off by one day. The problem seems to be related to timezones, as when data is added to the store it shows up differently later on. For example, 2013-03-31 becom ...

Can you explain how data fetching differs between refreshing the page and navigating to it?

I currently have a component named results.js, which is responsible for fetching data from our Back-end server. import { useRouter } from 'next/router'; import Navigation from '../../components/Navigation'; const Results = (props) => ...