【问题标题】:Prisma, TS and getServerSideProps, I'm stuckPrisma、TS 和 getServerSideProps,我被卡住了
【发布时间】:2022-01-04 02:08:58
【问题描述】:

我试图在我的 Nextjs 应用程序中通过 Prisma 进行简单查询,没有错误但无法返回任何结果,并且 console.log 在我的 getServerSideProps 中不起作用...

我错过了什么? CasinoComment 表中有数据(通过 axios 提交/添加),我可以通过 prisma studio 查看,我没有看到任何错误...

cmets.tsx

import { GetServerSideProps, GetStaticProps } from "next";
import { signIn, signOut, useSession } from "next-auth/react";
import { useRef, useState } from "react";

import { CasinoComment } from "@prisma/client";
import prisma from "../../lib/prisma";

type Props = {
  comments?: CasinoComment;
};

export default function Comment({ comments }: Props) {
 
  console.log(comments);
  ...
}


export const getServerSideProps: GetServerSideProps = async ({ params }) => {
  console.log("test222");

  const comments = await prisma.casinoComment.findMany();
  console.log(comments);
  return {
    props: { comments },
  };
};

schema.prisma

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider        = "prisma-client-js"
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  casino_comments CasinoComment[]
}


model CasinoComment {
  id          Int         @id @default(autoincrement())
  casinoId    Int
  content     String   @db.VarChar(2000)
  reply       Boolean?
  parentId    Int?
  approved    Boolean
  likes       Int?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @default(now()) @updatedAt
  author      User @relation(fields: [authorId], references: [id])
  authorId    String
}

lib/prisma.js

import { Prisma, PrismaClient } from "@prisma/client";

declare global {
  namespace NodeJS {
    interface Global {
      prisma: PrismaClient;
    }
  }
}

let prisma: PrismaClient;

if (typeof window === "undefined") {
  if (process.env.NODE_ENV === "production") {
    prisma = new PrismaClient();
  } else {
    if (!global.prisma) {
      global.prisma = new PrismaClient();
    }

    prisma = global.prisma;
  }
}

export default prisma;

【问题讨论】:

    标签: next.js prisma


    【解决方案1】:

    这对我很有用。

    export default function Comment(props: any) {
     
      console.log("Props are",  props); // to see data
      ...
    }
    
    
    export async function getServerSideProps() {
        const comments = await prisma.casinoComment.findMany();
        return {
          props: {
            comments: comments
          },
        };
      }
    

    【讨论】:

    • 我发现了问题...试图在组件中使用 getServerSideProps :( 但感谢您的努力!
    【解决方案2】:

    问题是我试图在组件中使用 getServerSideProps :/ 经验教训!

    【讨论】:

      猜你喜欢
      • 2023-02-09
      • 2016-11-06
      • 1970-01-01
      • 2017-01-12
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      相关资源
      最近更新 更多