Asynchronous JavaScript Tutorial #9 - The Fetch API

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

Key Takeaways

Demonstrates how to make fetch requests using the Fetch API in JavaScript

Full Transcript

okay then so far when we've been making http requests we've been using the xml http request object to do that and that is completely fine to do and many developers still use this way of working however there is a newer and quicker way to make these requests using the native fetch api which is now built right into the language now this is a fairly modern addition to the language and it's going to require us to write much less code than the older way using the xml http request object and it's also going to implement the promise api under the hood which is going to make handling success in error cases easy too now you might be sitting there asking yourself why i put you through all the misery of learning the older way when there is a newer and easier way to work and the reason my friends is not to annoy you it's so you have a great understanding of what's actually happening when we make these requests and to learn all about how callbacks work with requests and promises to so now you know all that and hopefully you understand the different moving pieces i can show you a more simplified approach to getting data which implements all of these things so to do this we're going to use the newer native fetch api which is just a function built right into the language and we can call it by just saying fetch like so it's as simple as that now in this function we pass in an argument which is the resource that we want to fetch now that could be some end point to an api like the json placeholder api we used before or it could just be a local resource like these things on the left i'm going to just grab one of these local resources so we'll say to do's to go into the to-dos folder then luigi.json that is the resource we want to get now this thing right here this returns to us a promise and remember a promise is basically saying look at some points i will either resolve if we have a success or reject if there's an error now when a promise is returned to us like this we can tack on the dot then method to fire a function when we have a success case when the promise is resolved so let's create that function and also down here we can tack on a dot catch method which is going to fire a callback function when there is an error so we have these two functions one for resolve and one for a reject now in the resolve over here we can take a response object and in the reject case in catch we can take an error object now what i'm going to do for now is just console.log over here and i'm going to say resolved and also the response and down here i'm going to say console.log and i'm going to say rejected and i'm also going to output the error okay then so before we look at this right here what i'd like to do is show you how the errors work with the fetch api now if i just type on an s to the end over here which doesn't exist now because we're looking for luigi's instead of luigi what do you think will happen do you think that this promise will be rejected and then this callback function fired well you would think not but if i save it we can see we still get the error but we get resolved and we get this response so the way the fetch api works is that the promise is only ever rejected when we get some kind of network error for example if we're offline or we can't reach the api for some reason so that's when we get a rejection if we just mistype the url over here or the end point or the resource then we don't get a rejection it's not rejected instead it's still resolved and we get the response however in the response if we expand that we can see we have a status of 404 which basically means the resource can't be found so in here we could still do a check for the status to make sure it's 200 before we do something with the data and then log out an area if we get a 404 or something and that is the case for our own error but if there's a network error and we can't for whatever reason reach the resource then it's going to reject and we're going to fire this callback function okay so then let's change this to the correct url i'm going to save it and check this out and now we can see resolved and we get this response object right here so we have all of this different data on the response object and this object is something that the fetch api creates for us when we go out and get data and it's returned to us this response object so now we can see the status is 200 the status text is okay we can see the url that we went to get the data from etc now one thing we can't see right here is the actual data that we returned remember we're ultimately looking for this json data and we can't see that anywhere inside here even if i expand the body i can't see any data in here now if we open up the proto remember this is where a lot of the methods are found inside an object let me scroll down here we can see this method right here called json so what we can do is use this method on the response object and that actually gets us the data we need so inside here when we get that response we could say response dot json now this method right here gets us the data and it passes it much like before we used json.pass this right here gets us the response data and it passes it so that we can use it inside our code easily now whereas before when we did json.pass we could do something like this we could say const the data is equal to json.pass and then whatever we want to pass this time this won't work and the reason is because response.json right here this returns a promise so remember a promise is something that typically takes a little bit of time to do and it can either be rejected or resolved so if this is returning a promise what we could do is instead say return right here so the overall value the return value of this thing is this promise right here and since the overall value is now returning a promise what we can do is tack on another then method right here and this is the power of promise chaining again now inside here we can actually take the data that we get back from the json method so this returns to us a promise which when resolved gives us the data that we need the data that we went out to fetch so now if i say console.log down here and then output the data now we have access to that so save it and we can see right here now we get all of that data awesome so then in the future when we're making some kind of network request for data i'm probably going to be using this way to get some kind of json rather than the older way of using an xml http request object because this is much less code to write and much easier to maintain so again all you need to remember are the three steps first of all we fetch the data then we take the response and we return response.js that returns a promise so we can tack on dot then to here and inside we fire a function where we actually have access to that data we can also catch an error at the end

Original Description

Hey gang, in this async javascript tutorial we'll take a look at how to make fetch requests using the fetch api. Get the full Modern JavaScript tutorial on Udemy here (discount auto-applied): https://www.thenetninja.co.uk/udemy/modern-javascript 🐱‍👤🐱‍👤 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 - http://www.thenetninja.co.uk/udemy/vue-and-firebase + D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase 🐱‍💻 🐱‍💻 Helpful Links: + 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 AI Lessons

Had my Frontend Developer interview with Capgemini (Application Developer) today, and I wanted to…
Prepare for a frontend developer interview with Capgemini by reviewing JavaScript fundamentals and practicing common interview questions
Medium · JavaScript
10 Frontend Developer Tools to Boost Productivity in 2026
Boost frontend productivity with 10 essential tools for modern web app development
Medium · Programming
10 Frontend Developer Tools to Boost Productivity in 2026
Boost frontend productivity with top 10 developer tools in 2026
Medium · JavaScript
The US Frontend Engineer Market in 2026: A Data-Driven Reality Check (and the Bias That Stops Us Seeing It)
US frontend engineer hiring demand peaked in 2022 and remains flat-depressed in 2026, contrary to common assumptions
Dev.to AI
Up next
The masks we wear | Zora Krstić | TEDxLuxembourgCity
TEDx Talks
Watch →