Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fetch does not work when using manual suspense #67285

Open
pedroalmeida415 opened this issue Jun 28, 2024 · 4 comments
Open

fetch does not work when using manual suspense #67285

pedroalmeida415 opened this issue Jun 28, 2024 · 4 comments
Labels
bug Issue was opened via the bug report template. Pages Router Related to Pages Router.

Comments

@pedroalmeida415
Copy link

pedroalmeida415 commented Jun 28, 2024

Link to the code that reproduces this issue

https://stackblitz.com/edit/stackblitz-starters-zpfjcc?file=app%2Fpage.tsx

To Reproduce

Enter demo and check terminal/console

Current vs. Expected behavior

I'm suspending a client component in order to fetch data necessary to render the component, but inside the callback, the window object is not defined, even though at this stage it should very much have access to it.

Removing window.location.origin will lead to another error: TypeError: Failed to parse URL from /multipliers.bin which I believe is because it doesn't have access to the window object in the first place, much like trying to do new URL('/multipliers.bin')

The library being used to suspend (suspend-react) has nothing to do with the problem, I tested without it by manually throwing a Promise and it still happens, kept it in for better code readability.

The versions of Next/React being used in the demo are not the latest ones because I couldn't get them to work on stackblitz, but I did try locally with the latest releases and the error still persists

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP Fri Mar 29 23:14:13 UTC 2024
  Available memory (MB): 7947
  Available CPU cores: 8
Binaries:
  Node: 20.8.1
  npm: 10.1.0
  Yarn: 1.22.19
  pnpm: N/A
Relevant Packages:
  next: 14.2.4 // Latest available version is detected (14.2.4).
  eslint-config-next: 14.2.4
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.4.5
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Pages Router

Which stage(s) are affected? (Select all that apply)

next dev (local), next build (local)

Additional context

When running build, next throws Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error. It seems like it is trying to pre render a client component but I have no idea why.

@pedroalmeida415 pedroalmeida415 added the bug Issue was opened via the bug report template. label Jun 28, 2024
@github-actions github-actions bot added the Pages Router Related to Pages Router. label Jun 28, 2024
@pedroalmeida415
Copy link
Author

pedroalmeida415 commented Jun 28, 2024

It seems like Next.js really doesn't like that I use the suspense feature manually on a Client Page route, and it runs the request in a server environment even though it's not

Considering the following route structure, where both Page and Home are client components:

// app/page.tsx
<Suspense fallback={<div'>loading...</div>}>
  <Home />
</Suspense>

Inside <Home /> I'm fetching data that will be used to display the contents of the page (it can't be a server component)

The fecthing goes like this:

// suspend() is using suspend-react library - I also tried without it (just throwing a Promise and managing state manually)
// AND with react-query, both yield the same error
async function getMultipliers() {
      const res = await fetch(`/multipliers.bin`)
      const buffer = await res.arrayBuffer()
      const decompressedStreamBuffer = LZMA.decompressFile(buffer)
      const rawBytes: Uint8Array = decompressedStreamBuffer.toUint8Array()

      return rawBytes
}

const multipliersArray = suspend(async () => await getMultipliers(), [])

This correctly suspends the component and displays the fallback in the <Suspense /> tag, but I get an error in the console:

react-dom.development.js:17497 Uncaught 
Error: Failed to parse URL from /positions.bin
    at updateDehydratedSuspenseComponent (react-dom.development.js:17497:1)
    at updateSuspenseComponent (react-dom.development.js:17193:1)
    at beginWork$1 (react-dom.development.js:18509:1)
    at beginWork (react-dom.development.js:26927:1)
    at performUnitOfWork (react-dom.development.js:25748:1)
    at workLoopSync (react-dom.development.js:25464:1)
    at renderRootSync (react-dom.development.js:25419:1)
    at performConcurrentWorkOnRoot (react-dom.development.js:24504:1)
    at workLoop (scheduler.development.js:256:1)
    at flushWork (scheduler.development.js:225:1)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:534:1)

Now, I managed to hack my way around this error by dinamycally importing the <Home /> component and explicitly setting the ssr to false in the options:

const Home = dynamic(() => import('@/components/home/home').then((mod) => mod.Home), {
  ssr: false,
  loading: () => <div>loading...</div>,
})

With this, the error goes away, but I'm left wondering why it even happened in the first case

This <Home /> component shouldn't even exist, it should just be the content of the app/page.tsx component, which combined with an app/loading.tsx component gives the exact structure needed to use suspense, so I'm convinced there's something wrong going on here

@pedroalmeida415
Copy link
Author

Accidentaly pressed the hotkey to comment and close, my bad

@pedroalmeida415 pedroalmeida415 changed the title window is not defined after suspending client component fetch does not work when using manual suspense Jun 28, 2024
@panukettu
Copy link

"use client" only means the code will be sent to the browser, it does not skip server rendering.

@jxdp
Copy link

jxdp commented Jun 29, 2024

@pedroalmeida415 "use client" does not mean "client only", it means "send all the JS to the client".

In a nutshell, you are trying to use the library as one would in a plain React application.

Try using useSuspenseQuery from react-query. You need to use hooks; if you only want to fetch in the browser, you would run the fetch inside useEffect and then suspend from there. Or you can save yourself a lot of effort and use react-query.

Or better yet, use a server component and let Next build your page statically: https://stackblitz.com/edit/stackblitz-starters-jcwjjf?file=app%2Fpage.tsx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Issue was opened via the bug report template. Pages Router Related to Pages Router.
Projects
None yet
Development

No branches or pull requests

3 participants