Full React Tutorial #19 - Handling Fetch Errors
Key Takeaways
Handles fetch errors in a React application using try-catch blocks
Full Transcript
so one more thing i want to do inside this component this home component is to handle any kind of error when we try to make this fetch right here now that could be an error which is sent back from the server or it could be a connection error where we can't even connect to the server so in that case we wouldn't be getting the data back and we need to let the user know that there's some kind of error so the first thing to do is add a catch block to this right here so let me do that and in fact i'm going to scoot this in a touch and then at the end of this then block i'll delete semicolon come down and say catch and this catch block catches any kind of network error and it will fire a function so i'm gonna put that error inside this function as a parameter and all i'm gonna do is log this to the console in fact we'll call this e double r and we can remove the parentheses all right so let me now console.log and we want to log the error dot message okay so this will catch any kind of network error so that's if we can't even connect to the server now we can simulate this kind of error if we open up the terminal and cancel out of this process from json server so that's what i'm going to do i'm going to press ctrl c to cancel out of this and press yes okay so now we shouldn't be able to connect to the server because it's not running and we should catch the error right here and then we're going to log that to the console so let me save this and refresh and open up the console so it tries to make the fetch you can see it's loading but then we see this error message right here failed to fetch so we can catch that error so that's a connection error but what if there's another type of error for example imagine our request reaches the server but the server sends an error back maybe if the end point that we've tried to fetch from doesn't exist or if the request is denied in that case this catch block over here doesn't automatically catch those errors when we use the fetch api because it's still reaching the server and the server is still sending a response object back to us it's just that the response doesn't contain the data and it will contain a different status now in this case we need to check that response object when we get it back so up here i'm going to do an if check and i'm going to say if then take the response object and i'm going to check the ok property on the response object and in fact before we do that what i'll do is comment this out and just log the response object to the console now we need to reconnect live server so i'm going to run this command again npx json server watch data forward slash db.json at port 8000 so press enter to watch that data again so this works but what i'm going to do is now just save this and come over here and refresh hopefully we'll see that response object do we no we don't console.log response we've not saved this that's why so save that and then we can see the response object right here now notice this we get this ok property and that means that the fetch was okay and we've got data back so that's true if everything is fine now if we don't get data back for example if we send a request to an endpoint that is faulty or that doesn't exist then this is going to be false so what i want to do is check is the response okay or rather is it not okay because if this okay thing is false then what i want to do is throw an error so let me uncomment this and i want to check not if the response is okay but if it's not okay so put an exclamation mark at the start of that so now if this is false and it's not okay the whole thing is true and it will fire this block of code and at this point i want to throw an error because it means that there's an error coming back from the server so i'll throw it right here like so this is how we throw an error and we'll enter in our own error message something like could not fetch the data for that resource now it can be anything you want it doesn't really matter so when we throw an error in this fetch it catches it down here so if it's not okay it throws the error we catch that error with the message attached to it so we should see that message in the console log now at the minute it's not gonna fire that message because the response is okay but if we change this to something that doesn't exist like add on another s that end point is faulty it's going to make the request to the server the server will send an error back so this will fire and then we throw our own error and we catch it over here so if we save this and refresh let's take a look it says could not fetch the data for that resource so then now we're catching the errors what i'd like to do is store the error in some kind of state so that we could output it to the browser so i'm going to first of all create some state at the top const error and set error and we're going to set that equal to use state and to begin with it's going to be null okay so when we catch the error over here instead of logging it to the console what i'm going to do is say set error and pass in the error dot message property so whatever message is on the error now that could be this or the network error message so now we have that what we could do is we could output it at the bottom if we have a value for error so again conditional rendering error double ampersand and then we'll output a div and then the error if we have one so only now if we have a value for error right here where we set the error will this output the error so if i save this now and preview notice could not fetch the data for that resource so that works however we still see loading and we don't want to see that if we have an error because it's not actually still loading so what we could do is if we get an error we also want to set this state right here is pending to be false so it doesn't show that loading message so i'll do that as well i'm going to say set is pending and that is going to be false now i also want to do one more thing and that is to set the error to be null inside here if we get data because if we try to fetch the data again make a subsequent request at any point we want to get rid of the error message if it's successful so over here i'm going to say set error and we're going to set it equal to null again all right so let's give this a whirl one more time i'm going to save this and let me get rid of those i'm going to refresh loading and then could not fetch the data for that resource so that works if we change this back to blogs let's make sure this still works refresh loading and then we get the data awesome
Original Description
Hey gang, in this React tutorial we'll handle any errors from the fetch request we made earlier & output any erors in the template.
🐱💻 🐱💻 Course Files:
+ https://github.com/iamshaunjp/Complete-React-Tutorial
🐱👤🐱👤 JOIN THE GANG -
https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg/join
🐱💻 🐱💻 My Udemy Courses:
+ Modern JavaScript - https://www.thenetninja.co.uk/udemy/modern-javascript
+ Vue JS & Firebase - https://www.thenetninja.co.uk/udemy/vue-and-firebase
+ D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase
🐱💻 🐱💻 Helpful Links:
+ HTML & CSS Course - https://www.youtube.com/watch?v=hu-q2zYwEYs&list=PL4cUxeGkcC9ivBf_eKCPIAYXWzLlPAm6G
+ Modern JavaScript course - https://www.youtube.com/watch?v=iWOYAxlnaww&list=PL4cUxeGkcC9haFPT7J25Q9GRB_ZkFrQAc
+ Get VS Code - https://code.visualstudio.com/
🐱💻 🐱💻 Social Links:
Facebook - https://www.facebook.com/thenetninjauk
Twitter - https://twitter.com/thenetninjauk
Instagram - https://www.instagram.com/thenetninja/
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Net Ninja · Net Ninja · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
More on: JavaScript Fundamentals
View skill →Related Reads
📰
📰
📰
📰
The Enter key that submits your form while a Japanese user is still typing
Dev.to · greymoth
The two-Reacts bug: when packages aren't singletons
Dev.to · r9v
🚀 Introducing Prism Guard — An Open Source Frontend Architecture Intelligence Platform
Dev.to · Ritumoni Sarma
The Death of the Heavy Hydration Layer
Dev.to · Amodit Jha
🎓
Tutor Explanation
DeepCamp AI