Estoy tratando de deshabilitar un botón solo si la solicitud de API es exitosa; de lo contrario, si no es exitosa, el botón aún debe estar habilitado. Tengo el siguiente campo de estado.
this.state = { buttonDisabled: false, };Aquí está mi botón:
<Button type="button" disabled={this.state.buttonDisabled} onClick={this.send} variant="outlined" color="primary"> Send </Button>Sin embargo, por alguna razón, el botón se desactiva durante 10 segundos en ambos casos. Respuesta aprobada y fallida de la API. ¿Hay algo aquí?
Su función sendSms() devuelve un objeto de Response axios. Por lo tanto, el objeto data siempre se completará y nunca se generará un error.
sendSmsCode = async () => { const { actions } = this.props; sendSms(phone) .then((data) => { // the data object is always populated with the response object and never throws an error // therefore, this function will always set the state to disabled this.setState({ requestSmsDisabled: true }, () => { actions.showSmsNotification(data); }); }) // this is never invoked .catch(err => actions.showSmsNotification(err)); setTimeout(() => { this.setState({ requestSmsDisabled: false }); }, 10000); };Debe verificar si hay un error en la respuesta de su llamada axios, ya sea en la función sendSms() o en la función sendSmsCode(), algo como:
async function sendSms(phone) { const options = { method: 'POST', headers: { 'content-type': 'application/json' }, data: { phone }, url: `${API_ROOT}/sms` }; // there are a number of ways to do this, it all depends on how you want to do it const response = await axios(options); if (response.status === 200) { return response.data; } else { // do something to indicate an error, eg throw an error to get caught in your .catch() statement or return an error message } }