Next lesson playing in 5 seconds

  • Overview
  • Transcript

7.1 The fetch() API

The new standard Fetch API is robust, allowing us to request and work with many different types of data (including binary). In this lesson, we'll use fetch() to retrieve our JSON file and then work with its data.

7.1 The fetch() API

In the early 2000s, it became popular to use JavaScript to make HTTP requests. And it greatly enhanced the user experience because it allowed us to partially update pages. Whereas before we would have to completely reload a page if there was anything that we wanted to update. Well, with JavaScript and the ability to make HTTP requests. We could do that partially so that if we needed to update just a single piece in the page, then we could do that without completely reloading the page. And now it's just commonplace. It's something that we do in almost every application. So in this lesson, I'm going to introduce you to the fetch API. We aren't going to really dive deep into it, but you will at least be familiar so that whenever you start immersing. And yourself in more in depth material, then you'll have an idea of how it works. So everything revolves around this function called fetch, and we basically pass in the URL of whatever it is that we went to fetch from the server. And right now we need something to fetch from the server. So let's go ahead and create a new file. Let's call this messages.jason. Now, Jason, it is Json that stands for JavaScript Object Notation. It looks like JavaScript, but it is not JavaScript, it is a Data Interchange Format that can be parsed into JavaScript. Now in a real application, we wouldn't be trying to fetch a static file, we would be hitting an endpoint in the server application. There would be some processing going on to where some data was retrieved from a database and then that would be returned. We don't have all of that infrastructure. So we are just going to work with this static file. And this is basically going to contain our messages. So that we will have our morning message which I believe was good morning. And then we will have our evening message, which was goodnight. Now, one thing I want you to be aware of are the quotes that I am using. Inside of our JavaScript file, I've been using single quotes to denote strings. Begins and ends with a single quote. Well, in java script strings can begin with a single quote or they can begin with a double quote, it doesn't matter as long as the beginning. And the ending quotes match. However, inside of our JavaScript code, I've been using single quotes because that is the common style that is used today. But when it comes to JSON. Well, the strings use double quotes. If we try to use single quotes, then we will end up with an error. So with a Jason file, that looks kind of like JavaScript, but the property names are strings. And in this particular case, the values are strings. They don't have to be strings. Like if we have a numeric value, can be a number, or if it's true or false, you know those can be the actual values. But since we are working with text, they of course have to be strings. So this is the file that we are going to fetch. And all we have to do is specify that file name whenever we call the fetch function. So we want to fetch messages.jason. and that is going to return what's called a promise. So let's do this, we're gonna create a variable called promise. Now, we aren't going to spend a whole lot of time going in depth as to what a promise is and all of that. The fetch operation is what's called an asynchronous operation. So whenever line 9 executes, it is going to go ahead and go out and fetch that resource on the server. But our JavaScript code is going to continue to execute. This is so that the operation of fetching the file on the server. Isn't going to block the rest of our code from executing. That's what we call asynchronous programming. If it did block the rest of our application from running, it will be called synchronous programming. Well, asynchronous programming is relatively complex, and it changes the way that we have to think about writing our code. Right now, I don't expect you to do that. But just know that this fetch function is returning what's called a promise. And a promise has a method called then so we are going to fetch our messages. And then we want to do something with that response. And we do something with that response with a callback function. So it's going to pass the response to this callback function, so that we can see what the actual response is. So let's just go ahead and let's write to that response to the console so that whenever we view this in the browser, We will see that response there it is right there. So we can drill into this and we can see kind of what comes with that response. So a few things we can see that the response was okay and that the status was 200. So this basically means that our fetch operation found that file, and it successfully received the contents of that file. However, there's really nothing here that we can use. I mean, there is the body of the response, but that is a stream and we would have to read that stream. So instead what we can do is, using a method called Jason. Since we know the data that is coming from the server is in JSON format, we can call this Jason method on our response. And that will convert everything into a JavaScript object. But here's the thing. This Jason method is also asynchronous. So we have to do kind of something like this. We have to return the conversion of the response to a json object, that is a promise. So we have to then work with the object that is created. So it's a little bit verbose as to what we have to go through in order to finally get something that we can work with. But to inside of here, we will finally have a JavaScript object that we can work with. And once again, if we view this in the browser, we are going to see that here is our object. It has an evening property and a morning property. So let's very briefly go back over this whole process, we are going to fetch our messages file. And then we are going to work with the response that comes back from the server. And the only thing that we want to do with that response is convert that json into an object. So then we can work with the object. Now, in the previous lesson, we created a few helper functions to make our code a little bit cleaner as we write it. We can essentially do the same thing so that we can have something like fetchJson and then we could specify the URL. And what we could do then is essentially take this code, at least as far as to the end of our first then and we will return that, we need to pass in the URL here. But this will make it so that's now, we can just say fetch json. We can get rid of this first then method, so that we can just have that second then method. So it's a little bit cleaner to understand. So we're going to fetch this json. So then we will work with the object that we are given. Now how do we use this inside of our code? Well, we could do this inside of our init. So that whenever we call the init method, the very first thing we do is go ahead and retrieve that message element. But then we could fetch our messages file. So that whenever we get the response, then we can set up the click event listeners, and that will give us the messages that we need. So here we could use our morning message and then for our evening, we could use the evening message. So with that, we can go to the browser, we can click on either one of these buttons, and the functionality is still the same. Except that now our messages are coming from our server. Now let's look at this Network tab in our developer tools. And it's going to show you all of the requests that were made. But here is the request for messages.jason. And we can see that we made the request and we got a response of 304. Now, this basically means that the file is modified since the last time that we requested it. But the request was made. If we look at the response, we can see the response that we get. And because we know we successfully made that request, and got the response, then we know that we are working with that data. So that is just a quick little tutorial on the fetch API. As I've mentioned that there is a lot of stuff that we could cover, but this at least get your feet wet and get you somewhat familiar with it.

Back to the top