简体   繁体   中英

Error handling for an api request in React

Im trying to handle errors with api calls. The goal is to show a button only when a successful response from the backend. Otherwise do not show the button. However, even when I get an error, the button will show. Here is my code:

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
         });
       });
   }

Here is where I am rendering the button:

{ (triggerShowButton ) && <Button className={classes.button} onClick= disabled={kycLevelTwoVerified} variant="contained" color="primary">Proceed</Button> }

The function

verify

is a function coming straight from another file. And I imported it. Here it is:

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);
}

The above code may not be relevant but I just show it here in case. Is there any way to make it so that the button is visible only on successful response?

it's always going to be true because you're telling it

, () => {
         this.setState({
           ...this.state,
           triggerShowButton: true
         });

you should probably put an if statment to check the status of the server or use .catch() incase of an error

like so

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)
         })

or alternate solution

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM