HialeahLiam
HialeahLiam

Reputation: 1

Next.js server-side data fetching within `Suspense` boundaries not supported yet

I'm reading the Next.js docs on how to use streaming server-rendering with React 18 and there's a section on data fetching that says the following:

Data fetching within Suspense boundaries is currently only supported on the client side. Server-side data fetching is not supported yet.

I understand that data can be fetched server-side only from pages, and the data would then be passed down to component through props. Does this mean we can't use getServerSideProps in pages that have components wrapped in Suspense, or just that we can't pass down fetch data to these components?

Upvotes: 0

Views: 3082

Answers (2)

Yilmaz
Yilmaz

Reputation: 49571

It is available with next13, app directory. Let's say we have two components, Orders and Users component

// fetch users
const getUsers=async ()=>{
    const res=await fetch(UserURL)
    return res.json}

const User=()=>{
 const users=getUsers()
 return (
 <> jsx here</>
 )}

Similarly "Orders" Component

 // fetch orders
const getOrders=async ()=>{
    const res=await fetch(OrderURL)
    return res.json }

const Order=()=>{
 const orders=getOrders()
 return (
 <> jsx here</>
 ) }

Let's say we have Admin Page and we render both components

import {Suspense} from "react"

const Admin=()=>{
 return(
       <>
       <Suspense  fallback=(<div>Loading Users</div>)>
            <Users/>
       </Suspense>

       <Suspense  fallback=(<div>Loading Orders</div>)>
            <Orders/>
       </Suspense>
       </>
 )}

Documentation shows data fetching with the new fetch API. I think somehow fetch api has to let React Suspense know that data fetching is complete so that React Suspense can render main jsx. I am not sure if other libraries do that

Another thing, in next.js app directory for each route, there is also loading.js file which will be automatically rendered while the main page is mounting. If Users component takes 1 second to fetch, and Orders component takes 2 seconds to fetch, loading.js content will be shown for 2 seconds till our Admin page is fully loaded. But with Suspense, after 1-second User component will be displayed, Orders component will be showing its own loading fallback till its fetching completed.

Upvotes: 0

Alex  Matei
Alex Matei

Reputation: 304

You can theoretically have a Suspense component in a page component, but it will be somewhat worthless. You won't get that page in the browser until the SSR hasn't rendered it. And when it does you'll get the full HTML, therefore having a Suspense does not add any value to the page component.

Because on the front-end you wait for data to come to you in order to modify the DOM, Suspense might bring some value, but for the SSR, I don't see any reason to implement it.

Upvotes: 0

Related Questions