Display a message after registration in NextJS
P粉909476457
2023-08-17 19:22:20
<p>I have a NextJS 13 application with a registration form. The API I'm integrating requires users to verify their email after signing up. What I want to do is, once the registration form is successful, remove the form fields and display a message telling them they need to check their email for a verification email, but instead it redirects all the way to the login form. I'm currently learning NextJS, so the code I'm using is taken from a sample repository. Is it possible to change it to display a message instead of redirecting to the login page? </p>
<p>My registration page looks like this:</p>
<pre class="brush:php;toolbar:false;">'use client'
import { useForm } from 'react-hook-form'
import { useUserService } from '@/app/_services'
export default Register
function Register() {
const userService = useUserService()
const { register, handleSubmit, formState } = useForm()
async function onSubmit(user) {
await userService.register(user)
}
return (
<>
<form
onSubmit={handleSubmit(onSubmit)}
>
<div className="col-span-full">
<label
htmlFor="email"
>
email address
</label>
<input
type="email"
{ ...register("email") }
/>
</div>
<div className="col-span-full">
<label
htmlFor="password"
>
password
</label>
<input
type="password"
{ ...register("password") }
/>
</div>
<div className="col-span-full pt-5">
<button
disabled={formState.isSubmitting}
>
<span>Register</span>
</button>
</div>
</form>
</>
)
}</pre>
<p>The actual registered function is in the <code>useUserService</code> file, with the following details: </p>
<pre class="brush:php;toolbar:false;">register: async (user) => {
alertService.clear()
try {
await fetch.post('/api/authentication/register', user);
router.push('/login');
} catch (error) {
alertService.error(error);
}
},</pre>
In order to display the message without redirecting to the login page, you can use the useState hook to manage the UI based on the registration success status.
);