Home > Back-end >  React Next.js: getServerProps is not returning array from prisma
React Next.js: getServerProps is not returning array from prisma

Time:06-08

Background

After learning enter image description here

CodePudding user response:

You cannot use getServerSideProps outside of pages directory. Change your code so that the prisma call is inside your page, and the posts are passed to Posts component using props. For example if you are displaying the posts in pages/index.js:

export const getServerSideProps = async () => {
  const prisma = new PrismaClient()
  const posts = await prisma.post.findMany()
    
  return { props: { posts } }
}

function Home({ posts }) {
  return (
    <Posts posts={posts}/>
  );
}

export default Home

Side note: You should not create a PrismaClient every time getServerSideProps is called. Create a prisma.js file, initialize it there and reuse when you need it:

import { PrismaClient } from '@prisma/client'

let prisma

if (process.env.NODE_ENV === 'production') {
  prisma = new PrismaClient()
} else {
  // Ensure the prisma instance is re-used during hot-reloading
  // Otherwise, a new client will be created on every reload
  globalThis.prisma = globalThis.prisma || new PrismaClient()
  prisma = globalThis.prisma
}

export default prisma
  • Related