Error Handling Data Requests
The course is part of this learning path
This module looks at how to work with External Data in React. You’ll be looking at Class Components, Effect Hooks, and how to handle data.
The objectives of this module are to provide you with an understanding of:
- The component lifecycle
- Hooks in React
- How to create restful services
- How to use an Effect Dependency Array
- How to hand errors in data requests
- How to send data
This learning path is aimed at all who wish to learn how to use the ReactJS framework.
We welcome all feedback and suggestions - please contact us at firstname.lastname@example.org to let us know what you think.
- When using the Fetch API you need to be mindful if a promise will resolve as long as the server sends a response therefore responses that have status codes such as 404 and 503, will appear to return valid data. Even though it's not the data we necessarily want. And the promise returned by the fetch call will resolve. We can see that when we request an ID that doesn't exist on the server, our app breaks. I set the course ID state to seven in the dropdown to make a request for an ID that doesn't exist in the courses stored on our server. As we can see on the JSON server console on the left of the screen, our request for ID seven returns with a 404 status. Our app render crashes, as there isn't any course objects in the array to render the course table from, with no course subjects, no course name exists. And the app fails when it tries to run a string function on a value that is undefined. So it's always good to deal with data returns that will cause problems before allowing the app to try and render that data. You will undoubtedly expect the data to be a particular data type, of a particular shape or some other features that will cause an error. If the data supplied is not what is expected. You can see that if we had a question mark, which is the syntax from all coalescing to the end of cost.name on line 13, it will only evaluate the result of the two lower case function. If course.name has a value. It will set it to undefined, otherwise. We've also done this into our new statement used to set search text match on line 14, where we only call index over on course name, lower case if course name lower cases is not equivalent to null. In this case it is, as it's undefined. The final alteration, is to change the return of the first condition match online 17, where we returned null, if the course name lowercase is equivalent to null. Rendering is in the browser and choose an option seven again means that our app is no longer error in the browser. However, we are breaking the prompt type rules we set, as shown on the browser console. So this is not an ideal fix. We can see that the server is still returning a 404 when we request ID seven. So perhaps we should leverage this. We can leave a no coalescing in place as it does no harm to handle a mistype course prompt. The trick is to filter the 200 status code, meaning okay. In the response and then handle any of the statuses accordingly, which at the condition of the response status before aligning state to be set. We must only let her response with a status code of 200 set the courses array in the course state. If we get anything else, we should set an error state and display an appropriate component. For a 404 status code, perhaps a 404 components. If we get any 500 errors, display an error component. In the rework code, for get courses function shown on line 17 to 31. It handles each of the status codes we want to using a couple of new components to display outputs accordingly. If we follow the same path of execution by selecting seven, from the dropdown the console still reports of 404 error but our application handles this gracefully and renders it as we have told it to adding a 404 component to the screen. An internal server error in the request that's in the 500 range, would be treated in the same way, displaying an error component with the status code and a message passed in his prompt. The conditional rendering has also been modified. This looks at the error state and decides what should be displayed below the Search bar. The component stored in the error state, the courses table or the loading message. So everything looks right? Wrong, what happens if the server does not respond? We'll look at that next. What if the fetch instruction fails? The promise will reject if reply is not received before the request times out or any of the network failure to deal with this, you should surround the fetch call in a try-catch block. When we do this, we seemingly handled the error gracefully. But now we have a warning on the console. The catch block on line 26 caused a new function called handle network error which generates an error component when the rejected promise is caught. Now that get courses potentially produces more than one output. We need to know if it changes as a result of the render. So if things get courses should be a dependency of the effect. Let's add that in and see what happens. The warning has changed and we're now making repeated requests for data, with repeated fails. The warning tells us that the get causes dependency makes the dependencies of the user fact hook change on every render. So it's called on every render. It suggests two things, moving the get courses declaration into the use of fact callback, which we've already tried to avoid once or app in the get courses definition in a use callback hook. Let's do that next. This is another inbuilt hook that gets an inline callback and an array of dependencies is arguments. The hook will return a memorized version of the callback. The only changes if one of its dependencies has changed. In our case we don't define any dependencies. So the same function will returned every time. It's just the result of its execution that may be different. We'll stop the JSON server and reload the application so that the fetch fails. Once we have this in place, the code now runs as we want it to where the error is handled and our app continues to run.
Ed is an Outstanding Trainer in Software Development, with a passion for technology and its uses and holding more than 10 years’ experience.
Ed is responsible for delivering QA’s Programming Foundations course using the Eclipse IDE. His skillset extends into the DevOps sphere, where he is able to deliver courses based around Agile/Scrum practices, version control, and CI/CD.