import{useState}from'react'import{useNavigate}from'react-router-dom'import'./Login.css'functionLogin({setUser}){constnavigate=useNavigate()const[mode,setMode]=useState('login')const[role,setRole]=useState('customer')const[form,setForm]=useState({first_name:'',last_name:'',email:'',password:'',address:''})const[error,setError]=useState('')consthandleChange=(e)=>{setForm({...form,[e.target.name]:e.target.value})}consthandleSubmit=async ()=>{setError('')if (!form.email){setError('Please enter your email');return}if (!form.password){setError('Please enter your password');return}if (mode==='register'){if (!form.first_name){setError('Please enter your first name');return}if (!form.last_name){setError('Please enter your last name');return}if (form.password.length<6){setError('Password must be at least 6 characters');return}constres=awaitfetch('/api/register',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(form)})if (!res.ok){setError('Registration failed');return}}consturl=role==='producer'?'/api/producer/login':'/api/login'constres=awaitfetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:form.email,password:form.password})})constdata=awaitres.json()if (!res.ok){setError(data.error);return}localStorage.setItem('user',JSON.stringify(data))setUser(data)navigate(data.role==='producer'?'/producer':'/')}return (<divclassName="login-page"><divclassName="login-card"><h1>{mode==='login'?'Log In':'Create Account'}</h1>
<divclassName="role-buttons"><buttononClick={()=>setRole('customer')}className={role==='customer'?'active':''}>Customer</button>
<buttononClick={()=>setRole('producer')}className={role==='producer'?'active':''}>Producer</button>
</div>
{mode==='register'&&(<><inputname="first_name"placeholder="First name"onChange={handleChange}/>
<inputname="last_name"placeholder="Last name"onChange={handleChange}/>
<inputname="address"placeholder="Address"onChange={handleChange}/>
</>
)}<inputname="email"placeholder="Email"onChange={handleChange}/>
<inputname="password"placeholder="Password"type="password"onChange={handleChange}/>
{error&&<pclassName="error">{error}</p>}
<buttonclassName="submit-btn"onClick={handleSubmit}>{mode==='login'?'Log In':'Sign Up'}</button>
<pclassName="toggle-link"onClick={()=>setMode(mode==='login'?'register':'login')}>{mode==='login'?'No account? Create one':'Already have an account? Log in'}</p>
</div>
</div>
)}exportdefaultLogin
Top comments (0)