Next.js Discord

Discord Forum

Suspense fallback for a Client-Side component

Unanswered
Cinnamon posted this in #help-forum
Open in Discord
CinnamonOP
I have a page like this:
import Page from "@/components/Page"
import PageSkeleton from "@/components/ui/PageSkeleton"
import { Suspense } from "react"

export default function Home() {
    return (
        <div>
            <Suspense fallback={<PageSkeleton />}>
                <Page />
            </Suspense>
        </div>
    )
}


the PageSkeleton only shows when the Page is a server side component,
so it's like this:

const getData = async () => {
    const res = await fetch("/api/data")
    const data = await res.json()
    return data
}

export default async function Page() {
    const data = await getData()

    return (
        <div>
            <h1>My Projects</h1>
            <ul>
                {data.map((something) => (
                    <li>{something}</li>
                ))}
            </ul>
        </div>
    )
}


This one works perfectly
but when I make it a client side component like this:

"use client"

import { useState, useEffect } from "react"

export default function Page() {
    const [data, setData] = useState([])

    useEffect(() => {
        const fetchData = async () => {
            const res = await fetch("/api/data")
            const data = await res.json()
            setData(data)
        }

        fetchData()
    }, [])

    return (
        <div>
            <h1>My Projects</h1>
            <ul>
                {data.map((something) => (
                    <li>{something}</li>
                ))}
            </ul>
        </div>
    )
}


this just shows nothing until the data is ready

5 Replies

Dunker
you dont have loading status at client component to show suspense fallback
@Dunker you dont have loading status at client component to show suspense fallback
CinnamonOP
and how I am supposed to do that? if you can edit my Client side example, would be appreciated
Dunker
[loading, setloading] = false

// in data fetch logic
  setLoading(true)

if (loading) <Fallback/>


  return (

   <Suspense fallback={<Fallback/>
CinnamonOP
I assumed you'd say that but the Suspense is in the Page that is importing all the components, and the client side is different component
CinnamonOP
Update: For now I used a isLoading state and conditionally rendered the proper JSX element.