Next.js Discord

Discord Forum

How to pass async data from the server component to the client component?

Answered
prerad posted this in #help-forum
Open in Discord
Hi, in my server component, I'm checking if is it the user's first time logging in, and I want to pass that data to the modal client component, which will show some kind of introduction message.

Do you know any way I can pass async data from the server component to the client component or it is just better to use client components for fetching rather than server components?
Answered by joulev
yes so then you can <IntroductionModal isFirstLogin={isFirstLogin}> – what's wrong with that?
View full answer

9 Replies

import createServerComponentClient from '@/lib/supabase-server'
import IntroductionModal from './IntroductionModal'

export default async function Home() {
  const supabase = createServerComponentClient()

  let isFirstLogin: null | boolean

  const {
    data: { session },
  } = await supabase.auth.getSession()

  if (session) {
    const { data: userData } = await supabase
      .from('users')
      .select()
      .eq('id', session.user?.id)

    if (userData?.length === 0) {
      isFirstLogin = true

      await supabase
        .from('users')
        .insert({ id: session.user?.id, email: session.user?.email })
    } else {
      if (!userData?.at(0)?.username) {
        isFirstLogin = true
      } else {
        isFirstLogin = false
      }
    }
  }

  return (
    <main>
      <IntroductionModal />
    </main>
  )
}
the problem is that isFirstLogin is nested
Answer
I thought it won't work xd
thanks
yeah it will work just fine
if you need to assert that isFirstLogin is non-null, then you can just do like
if (isFirstLogin === null)
  throw new Error("should never happen")
I will just add error handling for supabase 🙂