error-message icon indicating copy to clipboard operation
error-message copied to clipboard

NextJS static build throws error unless errors object passed to ErrorMessage

Open bennettrogers opened this issue 3 years ago • 8 comments

I've been using ErrorMessage with no issues on NextJS client-rendered pages. Based on the documentation, I haven't been passing the errors object to the ErrorMessage component since I'm using a FormProvider.

However, I just tried to use an ErrorMessage in a form on a NextJS statically exported page and it throws an error that says TypeError: Cannot read properties of null (reading 'formState').

After looking through the issues here and reading #52, I tried fetching the errors object inside my component using useFormContext, and passing this to the ErrorMessage. It seems to have resolved the issue.

This workaround works for me, but I wanted to see if this is expected behavior when exporting a static page.

Versions: NextJS v12.1.0 React-Hook-Form v7.27.1 @hookform/error-message v2.0.0

bennettrogers avatar Mar 11 '22 02:03 bennettrogers

Same here. Somehow this error was not triggered using next 11, but broke as soon as we upgraded to next 12. Error only occurs when server renders the page.

Simple replication sandbox here: https://codesandbox.io/s/cocky-hellman-toj9b9?file=/pages/index.js To replicate: remove the passed errors from ErrorMessage, and hit the refresh button in the sandbox browser. Passing the errors or downgrading to next 11 solves the issue.

IngoValente avatar Apr 12 '22 09:04 IngoValente

I can confirm this. Both with a Remix and vitest setup.

lennerd avatar Aug 04 '22 20:08 lennerd

I've just come across this issue as well.

{
    "@hookform/error-message": "^2.0.1",
    "next": "13.0.6",
    "react-hook-form": "^7.40.0"
}

dextermb avatar Dec 09 '22 11:12 dextermb

Same error with an NX workspace setup using webpack. It seems this library doesn't import the same version of the context

fknop avatar Mar 12 '23 20:03 fknop

Anyone found a workaround for this? Running into it with Vitest. We can just mock the component of course, but it would be nice to be able to include its functionality in our unit testing.

elramus avatar Jun 13 '23 19:06 elramus

Same error here, passing errors directly from the parent component solved the error.

...
  const methods = useFormContext();
  const error = get(errors || methods.formState.errors, name);
...

seems like methods from useFormContext returns 'undefined', still don't know why.

KirschX avatar Oct 31 '23 13:10 KirschX

Same issue here after update to NX v15.9.7

rtkac avatar Nov 15 '23 12:11 rtkac