Close

Learn ES6 Today with Vaadin Elements - Part 2: The Fetch API

In this segment of our guide to ES6, you’ll learn how to use the Fetch API to simplify your HTTP requests.

We will be referencing the example we wrote in the previous guide. You can read the first part of this blog series here: https://vaadin.com/blog/-/blogs/learn-es6-today-with-vaadin-elements-part-1-promises

The Fetch API

The Fetch API is not specifically an ES6 update, but rather a new API added to the browser. This API streamlines sending HTTP requests and processing the results. The API is extremely simple, and works entirely with Promises, so it matches up well with our existing code.

Using Fetch is as simple as calling fetch(url). This will run an HTTP GET request against that URL and return a Promise that will resolve to a Response object. From that Response object, you can just call response.json(), which itself returns a Promise will resolve to the results JSON.

Here’s a quick example of fetch:

// send request to url, get a Promise that resolves to the response
fetch(url).then(function(response) {
  // return a Promise that resolves to the response text as JSON
  return response.json();
}).then(function(json) {
  // use the JSON response
  console.log(json);
}

Learn about the Fetch API at MDN

Fetch in action

Let’s take a look at our example again. Follow along on jsbin to try the code yourself.

Since we're only changing the HTTP request code, we do all of our work getJSONPromise. The existing method returns a Promise that resolves to the JSON results, so we'll model our new method to return the same thing.

Our existing code looks like:

function getJSONPromise(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        resolve(JSON.parse(xhr.responseText));
      }
    };
    xhr.open('GET', url, true);
    xhr.send();
  });
}

Following the example above, we can rewrite all of that code to:

function getJSONPromise(url) {
  x = fetch(url).then(function(response) {
    return response.json();
  });
  return x;
}

That’s it!

Browser support

Fetch is currently supported by Edge, Chrome, Opera, and Firefox. Fetch is supported in the next release of Safari (10.1), but not in iOS Safari or IE 11. There is, however a polyfill available here. I have included this polyfill in the example in order to give support for all browsers.

Conclusion

The Fetch API is one more way the web platform is evolving to making coding simpler. Being able to run HTTP requests with one command means you can write the code you want without thinking about the details. When the constructs you use are streamlined, then your code itself will be clearer and more understandable.

In the next episode of our series on ES6 we’ll cover Arrow functions, a quick way to write more readable functions.

Learn more about <vaadin-grid> and Vaadin Elements

Vaadin 8 on tour

Vaadin Framework’s 8th release is almost here. And this really is a tentpole release. Whether you are already using an earlier version of Vaadin Framework, or just planning to use it, we are organizing an excellent way for you to see and hear what the new version really means for you - in person.

Meet us on the “Vaadin 8 tour” during spring 2017. Together with local Java User Groups, we are organizing Vaadin 8 events, talks and Q&A sessions all over the world for you to meet us.



Vaadin 8 on tour
 

Check out the map for upcoming events, and pick the one nearest to you. Or if you know of a place we should definitely visit, let us know and we’ll make it happen!

Visit vaadin.com/vaadin-8-roadshow

Use Item Templates with <vaadin-combo-box> to Customize the Item List

The Vaadin Elements team has just released a new update for <vaadin-combo-box> that enables custom item templates for combo box items. With custom templates, your combo box can consume the items array to display more complex HTML, such as including an index, adding an image, displaying multiple fields from the item data, or simply making the item bold or italic. Custom templates also allow you to display multiple fields from the data items, if you set the combo box’s items property to an array of objects.

For example:

<vaadin-combo-box items='[{"label": "Hydrogen", "value": "H"}]'>
  <template>
    [[index]]: [[item.label]] <b>[[item.value]</b>
  </template>
</vaadin-combo-box>

This will create a combo box where the items will be listed as:
1: Hydrogen **H**

Custom styles for item templates

With item templates, you can also style the displayed item. To do this, you need to create a new custom element with its own styles and template. You can also use any existing elements, such as <paper-item>, which is a natural fit for combo box items. The <paper-item> element can be easily used for this purpose.

For more information, see our docs page for Styling Combo Box Items with Custom Item Element.

Focused and Selected

There are several new variables you can bind from within the item template to further customize the displayed item. These variables are index, focused, and selected.

  • index displays the number index of that item, as shown in the first example above.
  • focused is true when the user is focused on that item, such as with keyboard navigation.
  • selected is true when the item is the selected item for the combo box.

Learn more about <vaadin-combo-box> at the Vaadin Elements page.