1- import React , { useState } from 'react'
2- import { Link } from 'react-router-dom' ;
1+ import React , { useContext , useState } from 'react'
2+ import { Link , useNavigate } from 'react-router-dom' ;
33
44import Form from '../../components/Form' ;
55import AuthLayout from '../../components/layout/AuthLayout' ;
66import ProfilePhotoSelector from '../../components/inputs/ProfilePhotoSelector' ;
77import Input from '../../components/Input' ;
88import Button from '../../components/Button' ;
9+ import axiosInstance from '../../utils/axiosInstance' ;
10+ import { API_PATHS } from '../../utils/ApiPaths' ;
11+ import { UserContext } from '../../context/userContext' ;
12+ import uploadImage from '../../utils/upload' ;
913
1014export default function SignUp ( ) {
1115 const [ profilePic , setProfilePic ] = useState < File | null > ( null ) ;
@@ -15,6 +19,13 @@ export default function SignUp() {
1519 const [ buttonText , setButtonText ] = useState ( "sign up" ) ;
1620 const [ adminInviteToken , setAdminInviteToken ] = useState ( "" ) ;
1721
22+ const navigate = useNavigate ( ) ;
23+
24+ const context = useContext ( UserContext ) ;
25+ if ( ! context ) {
26+ throw new Error ( "UserContext must be used within a UserProvider" ) ;
27+ }
28+ const { updateUser } = context ;
1829 const [ error , setError ] = useState ( "" ) ;
1930 const [ isShaking , setIsShaking ] = useState ( false ) ;
2031
@@ -27,6 +38,8 @@ export default function SignUp() {
2738 const handleSignUp = async ( e : any ) : Promise < void > => {
2839 e . preventDefault ( ) ;
2940
41+ let setProfilePicture = '' ;
42+
3043 if ( ! fullname ) {
3144 triggerError ( "Please enter fullname" ) ;
3245 return ;
@@ -45,9 +58,40 @@ export default function SignUp() {
4558 setError ( "" ) ;
4659
4760 try {
48-
61+ if ( profilePic ) {
62+ const imgUploadRes = await uploadImage ( profilePic ) ;
63+ setProfilePicture = imgUploadRes . imageUrl || "" ;
64+ }
65+
66+ const response = await axiosInstance . post ( API_PATHS . AUTH . REGISTER , {
67+ name : fullname ,
68+ email,
69+ password,
70+ setProfilePicture,
71+ adminInviteToken
72+ } ) ;
73+
74+ const { token, user } = response . data ;
75+
76+ if ( token ) {
77+ localStorage . setItem ( "token" , token ) ;
78+ updateUser ( response . data ) ;
79+
80+ if ( user . role === "admin" ) {
81+ navigate ( "/admin/dashboard" ) ;
82+ } else {
83+ navigate ( "/user/dashboard" ) ;
84+ }
85+ }
86+
4987 } catch ( err : any ) {
50-
88+ if ( err . response && err . response . data . message ) {
89+ triggerError ( err . response . data . message ) ;
90+ } else {
91+ triggerError ( "Something went wrong. Please try again." ) ;
92+ }
93+ } finally {
94+ setButtonText ( "sign up" ) ;
5195 }
5296 }
5397
0 commit comments