[BUG] Setting state in `onError` leads to React warning about setState called during render
- [x] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- [x] I have read the documentation and cannot find an answer.
Describe the bug
When passing a state setter to the onError prop of MDXEditor, React prints a warning similar to
hook.js:608 Cannot update a component (`DocumentPage`) while rendering a different component (`RealmWithPlugins`). To locate the bad setState() call inside `RealmWithPlugins`, follow the stack trace as described in https://react.dev/link/setstate-in-render
Reproduction https://stackblitz.com/edit/github-qekvbmto?file=package.json
To Reproduce Steps to reproduce the behavior:
- Navigate to the link above
- Open dev console
Expected behavior No errors or warnings are presented to the developer in the console
Desktop (please complete the following information):
- OS: macOS
- Browser: Chrome
Additional context
My hunch is this is due to the way gurx propagates values on change- perhaps instead of calling onError directly in the signal setup in the core plugin, using an effect would stop this from happening.
You can use a any kind of a delay mechanism in the setter to avoid that - that's what the internal implementation would do anyway.
I ended up doing this to quiet the error:
onError(({ error }) => setTimeout(() => setError(error), 0))
However, this could be broken in concurrent mode, since this is still a side effect during render.
Best practice would be to schedule it to run after the MDXEditor update that triggers the error is committed, i.e. via a useEffect
@lilactown I'm not certain on the canonical React way here, but would not throwing an Error + an ErrorBoundary around the component work too?
Yes, that would also work! And do away with the onError callback, I presume