0

I have a simple API call that sets the state of a list array with its response. I was wondering how I would go about implement a try/catch or error message if there is a bad search (i.e like a typo) or if the array is not set with the response. The code snippet is below:

componentDidMount() {
    this.search('https://itunes.apple.com/search?term=modern_baseball');
}

search(URL) {
   return $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function (response) {
            this.showResults(response);
        }.bind(this),
        error: function() {
            alert("Error handling request");
        }
    });
}

showResults(response) {
    console.log(response);
    this.setState({
        searchResults: response.results,
        moveResults: []
    });
}
1
  • I'm not sure I understand the question; you have success and error handlers, and you have your results. Create conditionals and set the state appropriately. Commented Jul 13, 2017 at 16:07

1 Answer 1

1

Try something like this:

componentDidMount() {
    this.search('https://itunes.apple.com/search?term=modern_baseball');
}

search(URL) {
  let self = this; //avoid the .bind call and store a ref to the current context for use inside the ajax handlers.
   return $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function (response) {
            self.showResults(response);
        },
        error: function() {
            alert("Error handling request");
            self.setState({error: "Error handling request", moveResults:[], searchResults:[]}); //set the state directly if there is an error
        }
    });
}

showResults(response) {
    console.log(response);
    this.setState({
        searchResults: response.results,
        moveResults: []
    });
}

It sets a variable (self) to the current context (this) and then calls the setState directly in the error handler for the ajax call. Alternatively you could define a callback function just like you do for the success handler.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.