Samyak jain
Samyak jain

Reputation: 137

Not able to submit form second time in a row in react

I am making a registration/login system in a mern app and i am facing a problem , the thing is whenever i register for the first time it works perfectly i get redirected to verification page submit my otp there and then get redirected to the home page (login/register page) but the problem is after coming to this page if i try to register again with diffrent credentials it neither redirect me to the verification page nor i see anything happening in my backend , only one thing happens that is my page reloads and all the creds that i entered get added in my url like this : - http://localhost:3000/?first_name=somename&second_name=somesecondname&[email protected]&new_password=password123&date=2022-01-29&gender=Male here is my code which is related to it:- JSX:-

const postregister = async(e)=>{
        
        e.preventDefault(); 
        
        const {first_name,second_name,email,new_password, date , gender} = userregister;

        const res = await fetch('/register',{
            method:'POST',
            headers:{
                'Content-Type' : 'application/json'
            },
            body:JSON.stringify({
                first_name,second_name,email,new_password, date , gender
            }),
            
        })

        const data = await res.json();
        console.log(data)
        if(data.status === 201){
            Navigate(`/verify/${first_name}/${email}`);
        }

        else if(data.status === 202){
            setshowalert({...showalert, bool:'true',text:data.message,removealert:'false'})
        }

        else{
            console.log('something went wrong')
        }
        

    const handleregister = (e)=>{
        const name = e.target.name;
        const value = e.target.value;
        setuserregister({...userregister,[name]:value})
        console.log(value)

    }

Edit - I have found out that if I wait for 1 minute or maybe 30 seconds before submitting the next form my form gets submitted but it doesn't get submitted if I try to submit it right after I am redirected to the register page

Upvotes: 0

Views: 695

Answers (1)

Dominik Misiek
Dominik Misiek

Reputation: 104

Edit: If everything works, when you wait some time before sending next form and does not work when you do it instantly, there is possibilty that the firt request have no time to be served.

I often fix it in this way:

  1. Add new variable, like const [loading, setLoading] = useState(false);
  2. At the begging of sending-request function set state to true
  3. After response arrive (before redirect or setting errors) set state to false
  4. Set form's submit button to enable / disable depending of loading state

It prevent user to send next request, before the first one is not finished.

Upvotes: 1

Related Questions