Estoy tratando de manejar errores con llamadas api. El objetivo es mostrar un botón solo cuando una respuesta exitosa del backend. De lo contrario, no muestre el botón. Sin embargo, incluso cuando recibo un error, se mostrará el botón. Aquí está mi código:
handleSubmit = (e) => { const { firstName, lastName, country, region, address, city, actions } = this.props; e.preventDefault(); verify(firstName, lastName, address, city, region, country) .then((data) => { actions.showSuccessNotification(data); }, () => { this.setState({ ...this.state, triggerShowButton: true }); }); }Aquí es donde estoy renderizando el botón:
{ (triggerShowButton ) && <Button className={classes.button} onClick= disabled={kycLevelTwoVerified} variant="contained" color="primary">Proceed</Button> }La función
verificar
es una función que viene directamente de otro archivo. Y lo importé. Aquí está:
async function verifyLevelOne(firstName, lastName, addressLine1, city, region, country) { const options = { method: 'POST', headers: { 'content-type': 'application/json' }, data: { firstName, lastName, addressLine1, city, region, country }, url: `${BASE}/level1` }; return axios(options); }El código anterior puede no ser relevante, pero solo lo muestro aquí por si acaso. ¿Hay alguna forma de hacer que el botón sea visible solo en una respuesta exitosa?
siempre va a ser verdad porque tu lo estas diciendo
, () => { this.setState({ ...this.state, triggerShowButton: true }); probablemente debería poner una declaración if para verificar el estado del servidor o usar .catch() en caso de error
al igual que
verify(firstName, lastName, address, city, region, country) .then((data) => { actions.showSuccessNotification(data); },() => { this.setState({ ...this.state, triggerShowButton: true }).catch((error) => { //handle error console.log(error) })o solución alternativa
verify(firstName, lastName, address, city, region, country) .then((data) => { actions.showSuccessNotification(data); },() => { if(dataIsVerified){ // dataIsVerified = you need to check if the data is ok it's up to you i just made it up this.setState({ ...this.state, triggerShowButton: true }) } else {throw "error"}