preact icon indicating copy to clipboard operation
preact copied to clipboard

[nextjs] Preact renders 5x when error is thrown in render and cancels rendering route

Open wilsonpage opened this issue 3 years ago • 5 comments

Describe the bug This is a bug related to Preact with Next.JS. If there's a better place to post this please let me know :) When an exception is throw in the render phase of a clientside rendered page the Next.JS pages/_error fails to render.

To Reproduce

  • Repro: https://nextjs-preact-demo-wilsonpage.vercel.app/
  • Source: https://github.com/wilsonpage/next-preact-error-handling-bug

Steps to reproduce the behavior:

  1. Visit /
  2. Click link to render /failing
  3. Observe fails to JS console showing 5x render and exceptions

image

Expected behavior

  • Should only invoke pages/failing render once
  • Should then render pages/_error

wilsonpage avatar Jul 23 '21 14:07 wilsonpage

It looks like Next.js is repeatedly re-rendering the route (there are 5 calls to preact.render()), but I think this may be caused by Preact bubbling thrown errors past components with a componentDidCatch() method if that method doesn't set state (which theirs does not): https://github.com/preactjs/preact/blob/7e33abd70ceb32f19e82c281e6b4d35091920f6a/src/diff/catch-error.js#L24

Normally, componentDidCatch() needs to invoke setState/forceUpdate in order to mark the component as dirty and "claim" the error - Next seems to just be triggering a full re-render after a Promise tick.

I'd be down to remove this personally, though it's unfortunate to drop conditional error bubbling (kinda a useful feature) to get compat :/

developit avatar Jul 23 '21 14:07 developit

Can confirm - my PR fixes this, we'll just need to figure out whether the change is something Preact can land without breaking stuff (since it affects how Suspense works). You can try it locally:

yarn add https://pkg.csb.dev/preactjs/preact/commit/90a1d849/preact

developit avatar Jul 23 '21 15:07 developit

@developit any tips on what I should do here long-term? Is a fix in the works?

wilsonpage avatar Nov 05 '21 16:11 wilsonpage

Hello. Any updates on this? This problem still remains with Next 12.1.6, Preact 10.7.2

grefrit avatar May 15 '22 23:05 grefrit

Hello guys, any updates? I'm facing the same issue.

JLucasCAmorim avatar Jun 14 '22 17:06 JLucasCAmorim