1
1
import { zodResolver } from '@hookform/resolvers/zod' ;
2
2
import { useMutation } from '@tanstack/react-query' ;
3
+ import { AxiosError } from 'axios' ;
4
+ import { useState } from 'react' ;
3
5
import { useForm } from 'react-hook-form' ;
4
6
import { useNavigate } from 'react-router-dom' ;
5
7
import { z } from 'zod' ;
@@ -49,6 +51,7 @@ type ISignupFormSchema = z.infer<typeof signUpSchema>;
49
51
50
52
export const useSignupForm = ( ) => {
51
53
const navigate = useNavigate ( ) ;
54
+ const [ errorMessage , setErrorMessage ] = useState < string | null > ( null ) ;
52
55
53
56
const form = useForm < ISignupFormSchema > ( {
54
57
resolver : zodResolver ( signUpSchema ) ,
@@ -71,9 +74,25 @@ export const useSignupForm = () => {
71
74
mutationFn : signUp ,
72
75
onSuccess : ( _response , _params , _context ) => {
73
76
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
+
74
86
// TODO: Add email validation page OR sign user in
75
87
navigate ( '/' ) ;
76
88
} ,
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
+ } ,
77
96
} ) ;
78
97
79
98
const onSubmit = ( formData : ISignupFormSchema ) => {
@@ -90,5 +109,5 @@ export const useSignupForm = () => {
90
109
sendSignUpRequest ( payload ) ;
91
110
} ;
92
111
93
- return { form, onSubmit : form . handleSubmit ( onSubmit ) , status, isPending } ;
112
+ return { form, onSubmit : form . handleSubmit ( onSubmit ) , status, isPending, errorMessage } ;
94
113
} ;
0 commit comments