Search code examples
javascriptreactjserror-handlingsuperagent

Superagent error handling React Javascript


I am working on this API React App. I am using Superagent to get the API request. But I have trouble handling the error when there is no response. I get this Uncaught (in promise) Error: Unsuccessful HTTP response. I have tried to put all the code inside a try-catch, but that would not do the job still get the error. This is my code:

handleClick() {
var searchWord = this.refs.search.value;
var url = "https://restcountries.eu/rest/v2/name/" + searchWord + "?fullText=true";
Request.get(url).then((response) => {
  var res = JSON.parse(response.text);
  this.setState({
    name:res[0].name,
    flag:res[0].flag,
    capital:res[0].capital,
  });
});
}

I want to handle the error, to print out to the user that there was nothing found or something like that.


Solution

  • I think this should do it.

    Request.get(url)
      .then((response) => {
        var res = JSON.parse(response.text);
        this.setState({
        name:res[0].name,
        flag:res[0].flag,
        capital:res[0].capital,
      })
    .catch((err) => {console.log(err)});
    

    Basically you append a catch() after the then() method.