Coder Social home page Coder Social logo

fewpjs-use-fetch's Introduction

Use fetch()

Learning Goals

  • Explain how to fetch data with fetch()
  • Working around backwards compatibility issues
  • Identify examples of the AJAX technique on popular websites

Introduction

When it comes to making engaging web sites, we often find ourselves needing to send a lot of data (text, images, media, etc.) so that the page is exciting.

But browsers won't show anything until they've processed all the of that data. As a result, they show nothing. The screen stays blank and users experience "waiting."

Spanky waits

Too much waiting means visitors will click away and never come back. Web users expect sites to load quickly and to stay updated. Research shows that 40 percent of visitors to a website will leave if the site takes more than 3 seconds to load. Mobile users are even less patient.

To solve this problem and help provide lots of other really great features, we developed a technique called AJAX.

In AJAX we:

  1. Deliver an initial, engaging page using HTML and CSS which browsers render quickly
  2. Then we use JavaScript to add more to the DOM, behind the scenes

AJAX relies on several technologies:

Part of what makes AJAX complicated to learn is that to understand it thoroughly, you need to understand all these components. For the moment, however, we're going to gloss over all these pieces in this lesson. It just so happens that modern browsers have abstracted all those components into a single function called fetch(). While someone interviewing to be a front-end developer will be expected to be able to explain all those components above (which we will cover later), while we're getting the hang of things, we're going to simplify our task by using fetch().

Let's learn to use fetch() to apply the AJAX technique: a way to load additional data after information is presented to the user.

Explain How to Fetch Data with fetch()

The fetch() function retrieves data. It's a global method on the window object. That means you can use it simply by calling fetch() and passing in a path to a resource as an argument. To use the data that is returned by the fetch(), we need to chain on the then() method. We can see what this looks like below:

fetch("string representing a URL to a data source")
.then(function(response) {
  return response.json();
})
.then(function(json){
  // Use the data inside of `json` to do DOM manipulation
})

Now let's add some multi-line (/*...*/) comments (which JavaScript will ignore) to describe what's happening:

fetch("string representing a URL to a data source")
  /*
    Here we are calling `fetch()` and passing a URL to a data source as the
    argument. The function call returns an object that represents what the data
    source sent back. It does *not* return the actual content. (More about this
    later.)
  */

  .then(function(response) {
    return response.json();
  })

  /*
    Next, we call the then() method on the object that comes back from the
    `fetch()`. We capture the object into the `response` parameter so it can be
    passed as an argument into a callback function.
    
    Inside the callback function, we do whatever processing we need on the
    object, in this case, converting it into JSON using the built-in `json()`
    method. (Another commonly-used method is `text()`, which will convert the
    response into plain text.) Finally, we return the JSON-ified response. 
    
    Note that we *have to return* the content that we've gotten out of the
    response and converted to JSON in order to use the data in the next then()
    method call.

    This first callback function is usually only one line: returning the 
    content from the response after converting it into the format we need.
  */ 

  .then(function(json){
    // Use the data inside of `json` to do DOM manipulation
  })
  /*
    This time, the `then()` method is receiving the object that we returned
    from the first call to `then()` (our JSON-ified object, in this case). We
    capture the object in the parameter `json` and pass it into a second
    callback function, where we will write code to do DOM manipulation using
    the data from the fetch
  */

Top Tip: As always, we can name the parameters being used in our callback functions anything we like, but most JavaScript developers use response and json by convention. Following the same naming convention is optional, but it will make your code more readable to other developers.

Filling Out the Example

Let's fill out our base skeleton.

First, we'll provide a String argument to fetch(). As it happens, http://api.open-notify.org/astros.json will provide a list of the humans in space. You can paste this URL into a browser tab and see that the data uses a JSON structure.

JSON is a way to send a collection of data in the internet, formatted as a String. It just so happens that this string is written in a way that would be valid JavaScript syntax for an Object instance. Thus the name "JavaScript Object Notation", or JSON ("jay-sawn"). Programmers find it very easy to think about JavaScript Objects, so they often send "stringified" versions of Objects as responses.

The then() takes a function. Here is where you tell JavaScript to ask the network response to be turned into JSON. When you first start using fetch(), most of your first then()s are going have a callback function that looks like this:

function(response) {
  return response.json();
}

The final then() is when you actually get some JSON (the return from the first then()) passed in. You can then do something with that JSON. The easiest options are:

  • alert() the JSON
  • console.log() the JSON
  • hand the JSON off to another function.

We'll go for the console.log() approach:

function(json) {
  console.log(json)
}

STRETCH: But you should be able to imagine that you could do some DOM manipulation instead.

Here's a completed example:

fetch('http://api.open-notify.org/astros.json')
.then(function(response) {
  console.log(response);
  return response.json();
})
.then(function(json) {
  console.log(json);
});

kimmy wow

Let's perform a demonstration. Navigate to http://open-notify.org in an incognito tab. We need to go incognito to make sure that none of your browsing history intereferes with this experiment.

Open up DevTools and paste the following into the console:

fetch('http://api.open-notify.org/astros.json')
.then(function(response) {
  return response.json();
}).then(function(json) {
  console.log(json);
  console.log(`Holy cow! There are ${json["number"]} humans in space.`);
});

Simple fetch()

You might notice in the DevTools console that this chained method call returned a Promise. We'll cover that later.

Working Around Backwards Compatibility Issues

As you can see, fetch() provides us with a short way to fetch and work with resources. However, fetch() has only recently arrived in browsers. In older code you might see jquery.ajax or $.ajax or an object called an XMLHttpRequestObject. These are distractions at this point in your education. After working with fetch() you'll be able to more easily integrate these special topics.

The AJAX technique opens up a lot of uses!

  • It allows us to pull in dynamic content. The same "framing" HTML page remains on screen for a cooking website. The recipe on display updates without page load. This approach was pioneered by GMail whose nav area is swapped for mail content swiftly โ€” thanks to AJAX.
  • It allows us to get data from multiple sources. We could make a website that displays the current weather forecast and the current price of bitcoin side by side! This approach is used by most sites to render ads. Your content loads while JavaScript gets the ad to show and injects it into your page (sometimes AJAX can be used in a way that we don't entirely like).

Conclusion

Many pages use AJAX to provide users fast and engaging sites. It's certainly not required in all sites. In fact, using it could be a step backward if simple HTML would suffice. However, as sites have more and more material, the AJAX technique is a great tool to have.

Using fetch(), we can include requests for data wherever we need to in our code. We can fetch() data on the click of a button or the expansion of an accordion display. There are many older methods for fetching data, but fetch() is the future.

Resources

fewpjs-use-fetch's People

Contributors

geluso avatar ihollander avatar jenmyers avatar kcleland0818 avatar lizbur10 avatar maxwellbenton avatar meg-gutshall avatar rrcobb avatar sgharms avatar shanisebarona avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fewpjs-use-fetch's Issues

Use Incognito Tab

Had to open up index.html in an incognito tab in order to see the game of thrones titles

Hyperlink doesn't make sense

The hyperlink on the "asynchronous Input / Output" bullet under introduction points to the same URL as "the event loop" bullet.

example fetch to astros.json no longer works

Problem Description

Instructions are incorrect for sample code trying out fetch.

"Let's perform a trivial demonstration. Open up a new incognito tab in Chrome. Open up DevTools and paste the following:"

Executing the sample code in an incognito tab crashes my chrome console. It can't run on GitHub or a new tab page either. It only runs when executing in a tab for http://open-notify.org/ itself.

Running in incognito ends with "DevTools was disconnected" error.

Screen Shot 2019-03-11 at 3 20 26 PM

Various Failure Descriptions

Can't run fetch in Chrome Dev Tools on GitHub. Can't run

VM53:1 Refused to connect to 'http://api.open-notify.org/astros.json' because it violates the following Content Security Policy directive: "connect-src 'self' uploads.github.com www.githubstatus.com collector.githubapp.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com wss://live.github.com".

Can't fun fetch in Chrome Dev Tools in new tab page.

VM50:1 Mixed Content: The page at 'https://www.google.com/_/chrome/newtab?ie=UTF-8' was loaded over HTTPS, but requested an insecure resource 'http://api.open-notify.org/astros.json'. This request has been blocked; the content must be served over HTTPS.

It DOES work if you open the Chrome Inspector at their page http://open-notify.org/.

Resolution

Update instructions to tell people to navigate to http://open-notify.org/ and open their Chrome Dev tools from there.

Routing off on the part of curriculum for me

Thanks for raising this issue! Future learners thank you for your diligence. In
order to help the curriculum team address the problem, please use this template
to submit your feedback. We'll work on addressing the issue as soon as we can.

Please fill out as much of the information below as you can (it's ok if you
don't fill out every section). The more context we have, the easier it will be
to fix your issue!

Note: you should only raise issues related to the contents of this lesson.
If you have questions about your code or need help troubleshooting, reach out to
an instructor/your peers.


Link to Canvas

https://learning.flatironschool.com/courses/1882/pages/use-%60fetch-%60?module_item_id=259510

Add a link to the assignment in Canvas here.

What should be changed?

I was following along these lessons linearly, and the curriculum jumped over the "Objects" section and straight into Fetch, and then after reading the lesson on Fetch, it jumped into the "Objects" lab, skipping over the lesson for Objects, which is quite a long and important one. I was quite lost with the Objects lab and kept feeling like there was a piece missing, as there didn't seem to be a lot or problems with it on Slack. I don't know if it's a browser/cache issue on my end or a routing issue on your end, but someone should look into it. I was quite lost and wondering why it seemed like I would be thrown into a lab with concepts that hadn't been touched on yet.

Suggest your change here. Let us know what section or line of the Readme needs
to be updated, and any proposed corrections. Include the line number(s) if
possible.

Additional context

Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.