What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation

The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post based on the slug (postID). However, it was discovered that running Prisma inside body components is not feasible. Subsequently, the solution involves employing getStaticProps and getStaticPaths to query the post by its ID prior to build time.

Code

/post/[...slugs].tsx

The URL structure resembles:

localhost:3000/post/postID/PostTitle

For example:

localhost:3000/post/b513-ad29e3cc67d9/Post%20Title

import { Post, PrismaClient } from '@prisma/client';
import { GetStaticPaths, GetStaticProps } from 'next';
import { useRouter } from 'next/router';

type postByIdProps = {
  postById: Post
}

export default function PostDetail({postById}: postByIdProps) {

  return (
    <>
      <div>
        {postById.title}
      </div>
    </>
  );
}

export const getStaticProps = async(context: any)=>{
// React Hooks cannot be used here, creating a challenge in obtaining the slug name without the hook.
  const router = useRouter(); 
  const slugs: any = router.query.slugs;
  const postId = slugs?.[0].toString()
//Prisma
  const prisma = new PrismaClient()
  const postById = prisma.post.findUnique({
    where: {
      postId: postId,
    },
  })

  return postById
}


export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {

  return {
      paths: [], //indicates that no page needs be created at build time
      fallback: 'blocking' //indicates the type of fallback
  }
}

Answer №1

My solution worked for me, but I'm open to suggestions for improvement.

Learn How to Create a Fullstack App with Next.js, Prisma, and PostgreSQL

Solution Code

import { Post } from '@prisma/client';
import { GetStaticPaths, GetStaticProps } from 'next';
import prisma from '../api/prisma';

type postByIdProps = {
  post: Post
}

export default function PostDetail({post}: postByIdProps) {
  console.log("Post details:", post)
  return (
    <>
      <div>
        {post.title}
      </div>
    </>
  );
}

export const getStaticProps = async({params}: any)=>{
  const postId = params.slugs[0] //gets post ID
  const post = await prisma.post.findUnique({
    where:{
      postId: String(postId)
    },
  })

  return {
    props:{
      post
    }
  }
}

export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {

  return {
      paths: [], //indicates that no page needs to be created at build time
      fallback: 'blocking' //indicates the type of fallback
  }
}



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

Success function in Classic ASP with Ajax Form isn't functioning properly, but the complete function is working fine

When using Ajax and JS/Jquery, I am attempting to send a basic Contact form to a Classic ASP (aspemail) without reloading the page. <form id="form-submit" action="ASPEmail.asp" method="post"> Name<br> <input id="name" type="text"&g ...

What is the best way to bring files into your project from a different directory?

Recently, I've been working on an app that consists of a backend repo and 2 frontend repos. Now, I'm facing the challenge of sharing code between these two frontend repos. app/ mySecondApp/ Despite my efforts, I'm unable to successfully imp ...

Spinning wheel animation with React JS

Is there a way to incorporate a circular loading progress in react js? I would like for a spinner (font awesome icon-fa-circle-o-notch fa-spin) to appear for a few seconds after clicking the logout button like this, and then for the button text to change ...

Is it possible to run a Vue file autonomously, similar to an HTML file

When it comes to running html, we can rely on mainstream browsers such as Chrome. But is there a similar tool for vue files, like the browsers designed for html? ...

Encountering an issue when trying to send data with Axios client to the child component

I'm encountering an issue while attempting to pass data to a child component for rendering. import axios from 'axios'; import React from 'react'; import MovieCard from './MovieCard'; import { useState, useEffect } from ...

Rows that have been removed from an HTML table remain within the ReactDOM

After diving into JavaScript three months ago, I recently began learning React.js just two days back. While creating a simple TODO app, I noticed that when deleting a row, it disappears from the DOM but not from the React DOM. Can anyone shed some light ...

Populate an ASP Form using Javascript in Android Studio

Being relatively new to Android studio, I have been experimenting with various methods but now need some assistance. I am looking to input data into an ASP.NET Website-form using Android studio. The traditional JavaScript approach does not seem to be effec ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

Executing Firebase Cloud Functions to perform write operations within a database event function

Exploring the world of Firebase functions has been an exciting learning journey for me. This innovative feature is proving to be incredibly powerful and beneficial. I'm eager to utilize a function that can capture a database writing event, perform a ...

Is there a way to verify if the password entered by the user matches the input provided in the old password field?

I am trying to compare the user's password with the one entered in the "oldPassword" input field. The challenge is hashing the input from the "oldPassword" field for comparison. How can I achieve this? Please review my ejs file and suggest improvement ...

Implementing jQuery UI toggleClass method to seamlessly alternate between two distinct CSS classes

My goal is to toggle between two CSS classes on a selector click using Jquery UI .toggleClass(), but unfortunately, it's not producing the desired toggle effect. $(".toggle").click(function () { $(".archivePosts .columns").removeClass( "l ...

Javascript/jquery functions perfectly in all browsers except Firefox

This particular piece of code seems to be functioning properly in Internet Explorer 8, Chrome, and Safari, however, it is not working as expected in Firefox: <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></scr ...

Issue encountered in Angular app-routing module.ts: Type error TS2322: The type '"enabled"' cannot be assigned to type 'InitialNavigation | undefined'

When I recently updated my project from Angular 11 to 14, I encountered the following error when running "ng serve". Error: src/app/app-routing.module.ts:107:7 - error TS2322: Type '"enabled"' is not assignable to type 'InitialNavigation | u ...

Assistance for Angular 2 Style Guide within Atom: Feature Needed!

My manager uses Atom with a set of eight plugins specifically designed for Angular development. I have the same plugins installed on my system, but I seem to be missing a feature that he has. We're unsure which plugin or preference setting is required ...

Activate a pointer cursor when hovering over a TextField in Material-ui design

Hey there! I'm new to Material-ui/ReactJS and I have a question. I'm trying to change the cursor to a pointer when hovering over a Material-ui TextField, but it's proving to be quite challenging. The default behavior is 'cursor: text&ap ...

What is the best way to perform unit testing on a function component that includes React.useState() using jest and enzyme?

I'm working on a function component that utilizes React.useState() to handle the state of a drawer modal. My challenge lies in testing this function and its ability to modify state using jest enzyme, as I cannot access its state function due to it not ...

Revamp State before redirecting using React Router Dom

In my current project, I am facing an issue with redirecting after updating the state successfully. The technologies I'm using include React 16.12.0 and React Router DOM 5.1.2. Here's the scenario: I have a button that, when clicked, should updat ...

Having trouble figuring out how to update a list using ajax in Yii

I need to modify a JavaScript function that filters the content of a list. The current code looks like this: var id = $(this).data('id'); $.fn.yiiListView.update('contests-list', { data: {category: 2} }); I couldn't find any ...

Leveraging the results from a static React function

I am currently working on a React + Webpack project that supports JavaScript ECMAScript 6. Here is the code snippet I am trying to implement: class ApiCalls extends React.Component{ static uploadFiles(files) { // upload code if(success) { ...

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...