Tengo este código para iniciar la sesión de los usuarios. Actualmente, cuando presiono iniciar sesión, el botón permanece activo. Lo que quiero es deshabilitar el botón cuando se hace clic en el inicio de sesión y la solicitud actual está en curso. Intenté usar el estado que inicialmente es falso, y cuando hago clic en el botón se vuelve verdadero. Y cuando se realiza la carga, vuelve a ser falso. Pero realmente no funcionó o tal vez lo hice de manera incorrecta.
Aquí está el código:
import api from '../services/api' import { useState } from 'react' import { Link, useNavigate } from 'react-router-dom' import { validateFormDataForLogin } from '../validate' export default function LoginPage() { // form state const [formData, setFormData] = useState({ 'email': '', 'password': '', }) // using navigate const navigate = useNavigate() // function to handle the changes function handleChange(e) { // getting the required values const { name, value } = e.target // setting the state setFormData(prevFormData => ({ ...prevFormData, [name]: value, })) } // function to handle the submit async function handleSubmit(e) { // preventing page reload e.preventDefault() // validating the data const errorMessage = validateFormDataForLogin(formData) // if there is an error message then show that error message if (errorMessage) { alert(errorMessage) return } // if there is no error message then try to login the user try { // making a request for login await api.post('/api/user/login', { email: formData.email, password: formData.password, }) // redirect the user to the dashboard once logged in navigate('/dashboard', { replace: true, // so that when we hit back, we don't go to the login page again, and goes to the page before login }) } catch (error) { // alerting the error if (error.response) { alert(error.response.data.message) } } } return ( <div className='login'> <h1 className='login--title'>Login</h1> <div className='login--content'> <form className='login--form' onSubmit={handleSubmit}> <input type='text' className='login--form--input' placeholder='Email address' name='email' value={formData.email} onChange={handleChange} /> <input type='password' className='login--form--input' placeholder='Password' name='password' value={formData.password} onChange={handleChange} /> <p className='login--form--forgot_password'>Forgot Password</p> <input className='login--form--submit' type='submit' value='LOGIN' /> </form> <div className='login--row'> <span className='login--row--text'>Don't have an account?</span> <Link to='/register' className='login--row--link'>Register</Link> </div> </div> </div> ) }
Cualquier ayuda será apreciada.
Puede realizar un seguimiento del estado de carga en un estado separado:
const [isLoading, setIsLoading] = useState(false) async function handleSubmit(e) { setIsLoading(true) /* ... */ try { // making a request for login await api.post('/api/user/login', { email: formData.email, password: formData.password, }) setIsLoading(false) /* ... */ } catch (error) { setIsLoading(false) /* ... */ } }
Luego, deshabilite el botón Enviar si isLoading
es verdadero:
<input type="submit" disabled={isLoading} />
pseudocódigo
Puede usar una variable de estado para almacenar la desactivación/activación del botón. el valor predeterminado es falso. digamos que la variable es isDisabled
. Como const [isDisabled, setIsDisabled] = useState(false)
Use esa variable en la validación condicional en el botón como
<input className='login--form--submit' type='submit' value='LOGIN' disabled={isDisabled}
Debe mantener actualizado el estado de la variable mientras realiza su solicitud de API / en caso de éxito o falla