Full React Tutorial #19 - Handling Fetch Errors

Net Ninja · Beginner ·🌐 Frontend Engineering ·5y ago

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 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

Related Reads

📰
The Enter key that submits your form while a Japanese user is still typing
Learn how to prevent the Enter key from submitting a form while a Japanese user is still typing, and why it matters for user experience
Dev.to · greymoth
📰
The two-Reacts bug: when packages aren't singletons
Learn to fix the two-Reacts bug by understanding how to handle non-singleton packages in React applications
Dev.to · r9v
📰
🚀 Introducing Prism Guard — An Open Source Frontend Architecture Intelligence Platform
Learn about Prism Guard, an open-source frontend architecture intelligence platform, and how it can help improve codebase quality
Dev.to · Ritumoni Sarma
📰
The Death of the Heavy Hydration Layer
Learn why plain HTML is the new developer flex and how to simplify web development by ditching heavy hydration layers
Dev.to · Amodit Jha
Up next
The masks we wear | Zora Krstić | TEDxLuxembourgCity
TEDx Talks
Watch →