We'll handle any fetching errors using the .catch()
property of the axios
promise. We'll also add some indication for our users to let them know that we had a problem.
We'll do this by setting an error data property to true when we have an error and conditionally render an error message to the user.
Instructor: [0:00] How are we going to handle if the API fails or there's an error in the fetch? Axios is promise-based, so we can use the .catch() function to be able to do something with our error.
[0:13] If there is an error, we will .catch() the error. For the moment, let's console.log() the error, and let's break the URL. In our console, we see it's a "404 Not Found," so we are getting an error, but for our user, there's nothing to tell them that something's gone wrong. There are a number of ways that we could approach telling our user something's wrong.
[0:38] We could add an error Boolean, and if there is an error rather than console logging, we can say, this.error = true, and then in our UI where this ticket types components being rendered, so here, we could add a heading say "History," that only shows if there's an error and say, "Sorry, we're having trouble getting the ticket types. Try again later."
[1:16] If there's a correct data fetch, we get the ticket types. If there's not, we get an helpful error message for our user.