Next.js Discord

Discord Forum

How to interact with other components when using Suspense?

Answered
Havana posted this in #help-forum
Open in Discord
HavanaOP
After my async component finishes loading data, how should I retrieve the data in the parent component, such as its length? I tried passing props to the child component and modifying them after it finishes loading, but it seems didn't work.

here's example code

async function ListData() {
    const data = await fetchData()    
    
    return <>...</>
}

export default async function Page() {
    return (
        <main>
            <p>{data.length}</p>

            <Suspense fallback={<p>Loading data...</p>}>
                <ListData/>
            </Suspense>
        </main>
    )
}
Answered by fuma
I think you can use the Context API:
function Parent() {
  return <ContextProvider>
    <Length />
    <Suspense>...</Suspense>
  </ContextProvider>
}

"use client"
function ContextProvider({ children }) {
  const [data, setData] = useState();
  return <Context.Provider value={[data, setData]}>
    {children}
  </Context.Provider>
}

"use client"
function Length() {
  const [data] = useContext(Context)

  return <p>{data}</p>
}

Only the components that receive the data will be client component
View full answer

3 Replies

@Havana After my async component finishes loading data, how should I retrieve the data in the parent component, such as its length? I tried passing props to the child component and modifying them after it finishes loading, but it seems didn't work. here's example code js async function ListData() { const data = await fetchData() return <>...</> } export default async function Page() { return ( <main> <p>{data.length}</p> <Suspense fallback={<p>Loading data...</p>}> <ListData/> </Suspense> </main> ) }
I think you can use the Context API:
function Parent() {
  return <ContextProvider>
    <Length />
    <Suspense>...</Suspense>
  </ContextProvider>
}

"use client"
function ContextProvider({ children }) {
  const [data, setData] = useState();
  return <Context.Provider value={[data, setData]}>
    {children}
  </Context.Provider>
}

"use client"
function Length() {
  const [data] = useContext(Context)

  return <p>{data}</p>
}

Only the components that receive the data will be client component
Answer
Because you can't re-render a RSC on the client-side, you must put it in a client component