Next.js Discord

Discord Forum

Async/Await with Client Side Components

Answered
Golden northern bumble bee posted this in #help-forum
Open in Discord
Golden northern bumble beeOP
Next.js newbie here. Basically, I'm building a users page which fetches data with prisma (yes, the database does return data, already tested) and displays it onto the page. However, when navigating to the users page, it does not render anything unless the page is manually refreshed. Also, my navbar has a login handler which shows the status of a user's session (signed in or not), it was always in the loading state when I eventually refreshed the users page.

I did try logging the session status - however, I got an error saying async/await cannot be used with client side components, upon removing it, the page seemed to function as I explained before.

Attached a video for reference.

Here's the code to users/page.tsx :
"use client"

import { prisma } from '@/lib/utils/prisma'
import { HoverEffect } from '@/components/ui/Card'

export default async function Users () {
    const users = await prisma.user.findMany()
    console.log(users)
    const cardDisplay = users.map((user) => ({
        title : `${user.name}'s profile`,
        description : "description that i'll decide on later",
        link : `http://localhost:3000/users/${user.id}`
    }))

    console.log(cardDisplay)

    return (
        <div>
            <HoverEffect items = {cardDisplay}/>
        </div>
    )
}
Answered by Spectacled bear
Yep, you can't await in a client component so the Card is being rendered before the data fetch finished. Either fetch this on the server and await there, use useEffect to fetch data and rerender by updating state, or use a library (react query, swr).
View full answer

14 Replies

@Golden northern bumble bee it's a client component, I haven't used prisma before so can you tell me if you need it to be a client component?
@Arinji <@547322851146072086> it's a client component, I haven't used prisma before so can you tell me if you need it to be a client component?
Golden northern bumble beeOP
Yeah mate, the Card i'm importing is a client component
Ok in that case use useEffect and state
Like the react way
Golden northern bumble beeOP
hmm alright mate
Spectacled bear
Yep, you can't await in a client component so the Card is being rendered before the data fetch finished. Either fetch this on the server and await there, use useEffect to fetch data and rerender by updating state, or use a library (react query, swr).
Answer
Golden northern bumble beeOP
Yeah, it does seem to work with useEffect
Client components have code similar to the react way
So if you want the easy way of just fetching in a component, do so in a parent server component and pass it to the child client component