11import { zodResolver } from '@hookform/resolvers/zod' ;
22import { useMutation } from '@tanstack/react-query' ;
3+ import { AxiosError } from 'axios' ;
4+ import { useState } from 'react' ;
35import { useForm } from 'react-hook-form' ;
46import { useNavigate } from 'react-router-dom' ;
57import { z } from 'zod' ;
@@ -49,6 +51,7 @@ type ISignupFormSchema = z.infer<typeof signUpSchema>;
4951
5052export const useSignupForm = ( ) => {
5153 const navigate = useNavigate ( ) ;
54+ const [ errorMessage , setErrorMessage ] = useState < string | null > ( null ) ;
5255
5356 const form = useForm < ISignupFormSchema > ( {
5457 resolver : zodResolver ( signUpSchema ) ,
@@ -71,9 +74,25 @@ export const useSignupForm = () => {
7174 mutationFn : signUp ,
7275 onSuccess : ( _response , _params , _context ) => {
7376 form . reset ( ) ;
77+ setErrorMessage ( null ) ;
78+ const userID = _response ?. data ?. id ;
79+
80+ if ( userID ) {
81+ // TODO: Revalidate with is-authed User Svc EP and put as user
82+ // details provider on each route request
83+ localStorage . setItem ( 'cachedUserID' , userID ) ;
84+ }
85+
7486 // TODO: Add email validation page OR sign user in
7587 navigate ( '/' ) ;
7688 } ,
89+ onError : ( error : AxiosError ) => {
90+ if ( error . response ?. status === 409 ) {
91+ setErrorMessage ( 'User with this username or email already exists.' ) ;
92+ } else {
93+ setErrorMessage ( 'An error occurred. Please try again later.' ) ;
94+ }
95+ } ,
7796 } ) ;
7897
7998 const onSubmit = ( formData : ISignupFormSchema ) => {
@@ -90,5 +109,5 @@ export const useSignupForm = () => {
90109 sendSignUpRequest ( payload ) ;
91110 } ;
92111
93- return { form, onSubmit : form . handleSubmit ( onSubmit ) , status, isPending } ;
112+ return { form, onSubmit : form . handleSubmit ( onSubmit ) , status, isPending, errorMessage } ;
94113} ;
0 commit comments