How to trigger FormMessage to display an error when failed to login in NextAuth #2087
-
I tried to make a form with shadcn-ui form. When i send "false" credential to next auth it throw an error. And i want to display the error below the input field. How to trigger that?
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
In your code, you're using setError from react-hook-form to manually set an error message when the sign-in fails. However, you're not using this error state to display the error message in your form. To display the error message, you need to pass the error state to the FormMessage component. Here's how you can do it: <FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" placeholder="Password" {...field} />
</FormControl>
{errors.password && <FormMessage>{errors.password.message}</FormMessage>}
</FormItem>
)}
/> In this code, errors.password will be truthy if there's an error with the password field. If there's an error, the FormMessage component will be rendered with the error message. Please note that this assumes that your FormMessage component accepts children as a way to display the message. If it uses a prop instead, you'll need to adjust the code accordingly. For example, if it uses a message prop, you would do: {errors.password && <FormMessage message={errors.password.message} />} This way, when the sign-in fails and you call setError('password', { type: 'manual', message: errorMessage }), the error message will be displayed under the password field. |
Beta Was this translation helpful? Give feedback.
-
there's a leaner way to do this: instead of using
it will interact with the already running react-state-hook instance and will automatically update |
Beta Was this translation helpful? Give feedback.
In your code, you're using setError from react-hook-form to manually set an error message when the sign-in fails. However, you're not using this error state to display the error message in your form.
To display the error message, you need to pass the error state to the FormMessage component. Here's how you can do it:
In this code, errors.password w…