1- import React , { useState , useEffect } from 'react' ;
1+ import React , { useState , useEffect , useRef } from 'react' ;
22import { useNavigate } from 'react-router-dom' ;
33import { useAuth } from '@/contexts/AuthContext' ;
44import { apiClient } from '@/api/client' ;
@@ -20,6 +20,7 @@ export const Login: React.FC = () => {
2020 const [ isCheckingFirstRun , setIsCheckingFirstRun ] = useState ( true ) ;
2121 const { login, setUser } = useAuth ( ) ;
2222 const navigate = useNavigate ( ) ;
23+ const isSubmittingRef = useRef ( false ) ;
2324
2425 useEffect ( ( ) => {
2526 const checkInitialState = async ( ) => {
@@ -53,34 +54,53 @@ export const Login: React.FC = () => {
5354
5455 const handleRegister = async ( e : React . FormEvent ) => {
5556 e . preventDefault ( ) ;
57+ if ( isSubmittingRef . current ) return ;
58+ isSubmittingRef . current = true ;
5659 setError ( '' ) ;
5760
5861 if ( password !== confirmPassword ) {
5962 setError ( 'Passwords do not match' ) ;
63+ isSubmittingRef . current = false ;
6064 return ;
6165 }
6266
6367 if ( password . length < 6 ) {
6468 setError ( 'Password must be at least 6 characters' ) ;
69+ isSubmittingRef . current = false ;
6570 return ;
6671 }
6772
6873 if ( username . length < 3 ) {
6974 setError ( 'Username must be at least 3 characters' ) ;
75+ isSubmittingRef . current = false ;
7076 return ;
7177 }
7278
7379 setIsLoading ( true ) ;
7480
7581 try {
7682 const result = await apiClient . register ( username , password ) ;
77- // Set user in auth context
7883 setUser ( result . user ) ;
7984 navigate ( '/' ) ;
8085 } catch ( err ) {
81- setError ( getErrorMessage ( err ) ) ;
86+ const message = getErrorMessage ( err ) ;
87+ // If user was already created (double-submit or lost response),
88+ // try logging in with the same credentials
89+ if ( message . toLowerCase ( ) . includes ( 'already exist' ) ) {
90+ try {
91+ await login ( { username, password } ) ;
92+ navigate ( '/' ) ;
93+ return ;
94+ } catch {
95+ setError ( 'An account already exists. Please sign in with your credentials.' ) ;
96+ setIsFirstRun ( false ) ;
97+ return ;
98+ }
99+ }
100+ setError ( message ) ;
82101 } finally {
83102 setIsLoading ( false ) ;
103+ isSubmittingRef . current = false ;
84104 }
85105 } ;
86106
0 commit comments