Search code examples
reactjsnext.jsprisma

How do I map prisma object in a NextJS 13 app router


I use prisma (with sqlite) and have User model store id, name, email. In the file, /alluser/page.tsx, I have this function to read for prisma data.

export async function getAllUsers(){
const prisma = new PrismaClient()
const users = await prisma.user.findMany()
    
 return{
 users
}

from the function I got user object in the form of

[{id:1, email:'email1', name: 'name1'},{id:2, email:'email2', name: 'name2'}]

and in export default function I use

export default function AllUser() {

    const users = getAllUsers()
    
    return (
      <main className="flex min-h-screen flex-col items-center justify-between p-24">
        <h1> All User </h1>
            {users.map((user) => (
            <li key={user.id}>
              <div>{user.name}</div>
              <div>{user.email}</div>
            </li>
          ))}
      </main>
    )
}

I tried console log users from the function AllUser() and I got

Promise { { users: [ [Object], [Object], [Object] ] }, [Symbol(async_id_symbol)]: 1088649, [Symbol(trigger_async_id_symbol)]: 1088647, [Symbol(kResourceStore)]: undefined, ...

I tried using parse and stringify but still got TypeError: undefined is not a function (near '...data.map...')


Solution

  • I guess you forget to await for promise:

    get-all-users.ts:

    export async function getAllUsers(){
      const prisma = new PrismaClient()
      const users = await prisma.user.findMany()
        
      return users
      
    }
    

    Page component should be async page.tsx:

       export default async function AllUser() {
    
        const users = await getAllUsers()
        
        return (
          <main className="flex min-h-screen flex-col items-center justify-between p-24">
            <h1> All User </h1>
                {users.map((user) => (
                <li key={user.id}>
                  <div>{user.name}</div>
                  <div>{user.email}</div>
                </li>
              ))}
          </main>
        )
    }