Next.js Discord

Discord Forum

use hook cause infinite loop in client component

Unanswered
Dutch posted this in #help-forum
Open in Discord
DutchOP
Hi guys,

i have a client component using use hook to fetch some data but when i use it within the suspense , it cause infinite loop

dashboard.tsx
export default function Dashboard() {
  return (
    <Suspense fallback={<div>Loading ...</div>}>
      <Summary />
    </Suspense>
  )
}


summary component
"use client";
export default function Summary() {
  const {data} = use(getSummaryData());

  return <p>{data.total}</p>;
}


getSummaryData is an axios function (GET method)
import req from "@/lib/request/axios";
export const summary = async () => (await req.get('/api/summary')).data;


req.ts
"use client";
const instance = axios.create(options);

where is the problem ?

5 Replies

Pacific sand lance
const [promise] = React.useState(() => getSummaryData());
const {data} = React.use(promise);
DutchOP
@Pacific sand lance not worked
could someone give me a simple example for suspense with new use hook ?
Morelet’s Crocodile
I had a similar issue, I had to pass the promise from a server component to the client instead of importing the promise. Any ways here is an example of how to use a promise with use and suspense:
export default function Page() {
    const orgMembersPromise = fetchOrgMembers()
return (
    <>
      <Suspense>
        <OrgMembersFilter orgMemberPromise={orgMembersPromise} />
      </Suspense>
    </>
)}

------------------Different files------------------------------------

'use client'
export default function OrgMembersFilter({
      orgMemberPromise,
}: {
      orgMemberPromise: Promise<OrgMember[]>
}) {
      const orgMembers = use(orgMemberPromise)
return(.......

Step 1 Start promise on page or server component, do not use await
Step 2 pass promise as props to client component
Step 3 use use() to resolve promise
': {
orgMemberPromise: Promise<OrgMember[]>
} ' is not needed in JS only TS