DEV Community

Hasnain Ali
Hasnain Ali

Posted on

React useState Issue

Hey i'm working on a project where i will have to reset my fields after submitting form. When i try to reset the state to initial it revert back to previous state after some time. here is the code. `import React,{useState,useEffect} from 'react';
import { Navbar } from '../../components';
import { Footer } from '../Home';
import axios from 'axios';
export default function Signup() {

const initialState = {
    name:'',
    email:'',
    password:'',
    password_confirmation:'',
    scope:'patient',
    terms:false,
    error_list:[],
    error:'',
    success:'',
}
const [signupForm,setSignupForm]=useState(initialState);
useEffect(() => {
        console.log(signupForm);
},[signupForm]);

const handleForm=(e)=>{
    if(e.target.type=="checkbox"){
       if(e.target.checked){
        setSignupForm({...signupForm,terms:true});

       }else{
        setSignupForm({...signupForm,terms:false});
       }
    }else{
        setSignupForm({...signupForm,[e.target.name]:e.target.value});   
    }
}




function onSubmitFuction(event) {
    event.preventDefault();      
    const data={
        name:signupForm.name,
        email:signupForm.email,
        password:signupForm.password,
        password_confirmation:signupForm.password_confirmation,
        scope:signupForm.scope,
        terms:signupForm.terms,
    }



    axios.post(`/auth/signup`,data)
        .then(res=>{ 
            setSignupForm({...signupForm,success:res.data.data.message});

            setTimeout(function() {
                setSignupForm({...signupForm,success:false});
              }, 5000);
              setSignupForm({...initialState});
              event.target.reset();
              setSignupForm({...initialState});


        }).catch(function (error) {
            console.log(error);
            if(error.response.status===422){
                setSignupForm({...signupForm,error_list:error.response.data.errors});
            }else{
                setSignupForm({...signupForm,error:error.response.data.error});
                setTimeout(function() {
                    setSignupForm({...signupForm,error:false});
                }, 5000);

            }
        });

        console.log( signupForm());
}



return (
    <div>
        <Navbar />

        <div className='flex w-full h-screen justify-center items-center '>
            <div className='flex flex-col md:flex-row md:space-x-6 space-y-6 contact md:space-y-0  w-full max-w-4xl p-8 rounded-xl shadow-lg text-white'>

                <div className='animate__animated animate__slideInRight  bg-white shadow-lg rounded-xl p-8 text-gray-600'>
                    <form  onSubmit={onSubmitFuction}  className='flex h-full flex-col space-y-8'>


                    {signupForm.error?
                            <div className="animate__animated animate__flipInX flex items-center justify-center px-4">
                                <div role="alert" id="alert" className="transition duration-150 ease-in-out w-full lg:w-11/12 mx-auto bg-white dark:bg-gray-800 shadow rounded flex flex-col py-4 md:py-0 items-center md:flex-row justify-between">
                                    <div className="flex flex-col items-center md:flex-row">
                                        <div className="mr-3 p-4 bg-red-400 rounded md:rounded-tr-none md:rounded-br-none text-white">
                                            <i className='fa fa-times'></i>
                                        </div>
                                        <p className="mr-2 text-base font-bold text-gray-800 dark:text-gray-100 mt-2 md:my-0">Error</p>
                                        <div className="h-1 w-1 bg-gray-300 dark:bg-gray-700 rounded-full mr-2 hidden xl:block"></div>
                                        <p className="text-sm lg:text-base dark:text-gray-400 text-gray-600 lg:pt-1 xl:pt-0 sm:mb-0 mb-2 text-center sm:text-left">{signupForm.error}</p>
                                    </div>
                                </div>
                            </div> : ""}
                    {signupForm.success?
                            <div className="animate__animated animate__flipInX flex items-center justify-center px-4">
                                <div role="alert" id="alert" className="transition duration-150 ease-in-out w-full lg:w-11/12 mx-auto bg-white dark:bg-gray-800 shadow rounded flex flex-col py-4 md:py-0 items-center md:flex-row justify-between">
                                    <div className="flex flex-col items-center md:flex-row">
                                        <div className="mr-3 p-4 bg-green-400 rounded md:rounded-tr-none md:rounded-br-none text-white">
                                            <i className='fa fa-check'></i>
                                        </div>
                                        <p className="mr-2 text-base font-bold text-gray-800 dark:text-gray-100 mt-2 md:my-0"></p>
                                        <div className="h-1 w-1 bg-gray-300 dark:bg-gray-700 rounded-full mr-2 hidden xl:block"></div>
                                        <p className="text-sm lg:text-base dark:text-gray-400 text-gray-600 lg:pt-1 xl:pt-0 sm:mb-0 mb-2 text-center sm:text-left">{signupForm.success}</p>
                                    </div>
                                </div>
                            </div> : ""}
                        <div className='my-auto'>
                            <div className='mb-6'>
                                <label className="py-6" htmlFor="">
                                    Name
                                </label>

                                <input type='text' name='name'  defaultValue={signupForm.name} onChange={handleForm} placeholder='Full Name' className='p-2 ring-1 ring-gray-300 w-full rounded-md px-4 py-2 outline-none focus:ring-2 focus:ring-purple'/>
                                {signupForm.error_list.name?<span className='text-rose-500'>{signupForm.error_list.name}</span>:''}
                            </div>
                            <div className='mb-6'>
                                <label className="py-6" htmlFor="">
                                    Email Adress
                                </label>

                                <input type='email' name='email'  defaultValue={signupForm.email} onChange={handleForm} placeholder='Email Adress ' className='p-2 ring-1 ring-gray-300 w-full rounded-md px-4 py-2 outline-none focus:ring-2 focus:ring-purple'>
                                </input>
                                {signupForm.error_list.email?<span className='text-rose-500'>{signupForm.error_list.email}</span>:''}
                            </div>
                            <div className='mb-6'>
                                <label className="  " htmlFor="">
                                    Password
                                </label>

                                <input type='password' name='password'  defaultValue={signupForm.password} onChange={handleForm} placeholder='Password' className=' ring-1 ring-gray-300 w-full rounded-md px-4 py-2 outline-none focus:ring-2 focus:ring-purple'>
                                </input>
                                {signupForm.error_list.password?<span className='text-rose-500'>{signupForm.error_list.password}</span>:''}
                            </div>
                            <div className='mb-6'>
                                <label className="  " htmlFor="">
                                   Confirm Password
                                </label>

                                <input type='password' name='password_confirmation'  defaultValue={signupForm.password_confirmation} onChange={handleForm} placeholder='Confirm Password' className=' ring-1 ring-gray-300 w-full rounded-md px-4 py-2 outline-none focus:ring-2 focus:ring-purple'>
                                </input>
                                {signupForm.error_list.password_confirmation?<span className='text-rose-500'>{signupForm.error_list.password_confirmation}</span>:''}
                            </div>
                            <div className='mb-6'>
                                <label className="  " htmlFor="">
                                    Registration type :
                                </label>

                                <div className="flex">
                                    <div className="flex items-center mr-4">
                                        <input id="inline-radio" type="radio" onClick={handleForm} value="patient" defaultChecked={signupForm.scope==="patient"?"checked":''}  name="scope" className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"/>
                                        <label htmlFor="inline-radio" className="ml-2 text-sm font-medium text-gray-900 dark:text-gray-300">Patient</label>
                                    </div>
                                    <div className="flex items-center mr-4">
                                        <input id="inline-2-radio" type="radio" onClick={handleForm} defaultChecked={signupForm.scope==="doctor"?"checked":''} value="doctor" name="scope" className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"/>
                                        <label htmlFor="inline-2-radio" className="ml-2 text-sm font-medium text-gray-900 dark:text-gray-300">Doctor</label>
                                    </div>
                                </div>
                            </div>
                            <div className='mb-6'>
                                <input type="checkbox" name='terms' onChange={handleForm} defaultChecked={signupForm.terms?'checked':''} />
                                <label className="pl-4" htmlFor="">
                                    I agree to <u>Terms & service</u> use.
                                </label>
                                {signupForm.error_list.terms?<span className='text-rose-500'>{signupForm.error_list.terms}</span>:''}
                            </div>
                            <button className='block w-full btn-contact text-white font-bold rounded-lg  px-6 py-2 uppercase text-sm mt-6'> Register Now </button>
                        </div>
                    </form>
                </div>

                {/* //contact */}
                <div className='animate__animated animate__slideInLeft flex flex-col space-y-8 justify-between'>
                    <div>
                        <h1 className='font-bold text-4xl tracking-wide'>Register Now</h1>
                        <p className='pt-2 text-sm'>Here our team will help you yo can call us or submit your query!</p>

                    </div>
                    <div>
                        <div>
                            <div className='inline-flex space-x-2 items-center' >
                                <svg xmlns="http://www.w3.org/2000/svg"
                                    className="h-5 w-5 absolute  "
                                    viewBox="0 0 20 20"
                                    fill="currentColor">
                                    <path d="M2 3a1 1 0 011-1h2.153a1 1 0 01.986.836l.74 4.435a1 1 0 01-.54 1.06l-1.548.773a11.037 11.037 0 006.105 6.105l.774-1.548a1 1 0 011.059-.54l4.435.74a1 1 0 01.836.986V17a1 1 0 01-1 1h-2C7.82 18 2 12.18 2 5V3z" />
                                    <path d="M16.707 3.293a1 1 0 010 1.414L15.414 6l1.293 1.293a1 1 0 01-1.414 1.414L14 7.414l-1.293 1.293a1 1 0 11-1.414-1.414L12.586 6l-1.293-1.293a1 1 0 011.414-1.414L14 4.586l1.293-1.293a1 1 0 011.414 0z" />
                                </svg>
                                <span className='p-6 pl-10'>+(92)3035957991</span>

                            </div>
                        </div>
                        <div>
                            <div className='inline-flex space-x-2 items-center' >
                                <svg xmlns="http://www.w3.org/2000/svg"
                                    className="h-5 w-5"
                                    viewBox="0 0 20 20"
                                    fill="currentColor">
                                    <path d="M2.003 5.884L10 9.882l7.997-3.998A2 2 0 0016 4H4a2 2 0 00-1.997 1.884z" />
                                    <path d="M18 8.118l-8 4-8-4V14a2 2 0 002 2h12a2 2 0 002-2V8.118z" />
                                </svg>
                                <span className='p-6'>ahtisham@gmail.com</span>

                            </div>
                        </div>
                        <div>
                            <div className='inline-flex space-x-2 items-center' >
                                <svg xmlns="http://www.w3.org/2000/svg"
                                    className="h-5 w-5" viewBox="0 0 20 20"
                                    fill="currentColor">
                                    <path fillRule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clipRule="evenodd" />
                                </svg>
                                <span className='p-6'>Rawalpindi,Tench Bhata</span>

                            </div>
                        </div>
                    </div>
                    <div>
                        <span className="inline-flex">
                            <a href='/#' className="text-gray-500">
                                <svg
                                    fill="currentColor"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth="2"
                                    className="w-5 h-5"
                                    viewBox="0 0 24 24"
                                >
                                    <path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z"></path>
                                </svg>
                            </a>
                            <a href='/#' className="ml-4 text-gray-500">
                                <svg
                                    fill="currentColor"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth="2"
                                    className="w-5 h-5"
                                    viewBox="0 0 24 24"
                                >
                                    <path d="M23 3a10.9 10.9 0 01-3.14 1.53 4.48 4.48 0 00-7.86 3v1A10.66 10.66 0 013 4s-4 9 5 13a11.64 11.64 0 01-7 2c9 5 20 0 20-11.5a4.5 4.5 0 00-.08-.83A7.72 7.72 0 0023 3z"></path>
                                </svg>
                            </a>
                            <a href='/#' className="ml-4 text-gray-500">
                                <svg
                                    fill="none"
                                    stroke="currentColor"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth="2"
                                    className="w-5 h-5"
                                    viewBox="0 0 24 24"
                                >
                                    <rect
                                        width="20"
                                        height="20"
                                        x="2"
                                        y="2"
                                        rx="5"
                                        ry="5"
                                    ></rect>
                                    <path d="M16 11.37A4 4 0 1112.63 8 4 4 0 0116 11.37zm1.5-4.87h.01"></path>
                                </svg>
                            </a>
                            <a href='/#' className="ml-4 text-gray-500">
                                <svg
                                    fill="currentColor"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth="2"
                                    className="w-5 h-5"
                                    viewBox="0 0 24 24"
                                >
                                    <path d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z"></path>
                                </svg>
                            </a>
                        </span>
                    </div>
                </div>
                {/* form */}


            </div>
        </div>

        <Footer />

    </div>
)
Enter fullscreen mode Exit fullscreen mode

}
`

Top comments (1)

Collapse
 
_bkeren profile image
'' • Edited

You're using setTimeout, asynchronous call.

even if you try to clear all, after 5 seconds, setTimeout will be called..

you should set sign up form once for an action