Step 1

Add the utility library

<script type="text/javascript" src="utils/utils.js"></script>

Remove the static object postToAdd with an actual ajax call.

note that we will print only the first item

fetch(FIREBASE_JSON)
  .then(function(response) {
    return response.json();
  })
  .then(function(posts) {
    var postToAdd = toArray(posts)[0];
    drawElement(postToAdd);
  });

What does this code do?

This code fragment looks pretty dense; we can phrase it as follows:

Retrieve the information at the address, prepare them for reading, take the first information piece and draw it

Now let's analyze it bit by bit (pun intended :) )

1.1 — thefetch() function

fetch(FIREBASE_JSON)

fetch() is a function that accepts some parameters, the first one is always an address, in this particular case FIREBASE_JSON.

FIREBASE_JSON is a string inside the file utils/utils.js, it's the specific address of our json on the database

1.2 — The first .then()

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

This is a dirty implementation detail.

This step is executed as soon as fetch() completes, hence it's named then().

We can manipulate the response with a function. A function always need a return statement, here we instrument the function to pass the response to the next step in some handy (json) format.

1.2 — The second .then()

  .then(function(posts) {
    var postToAdd = toArray(posts)[0];
    drawElement(postToAdd);
  });

The first line inside the function is a variable assignment, here we transform the posts from an object to an array, for convenience, and we take the first element (please note that the first element has index 0)

In the second line we can find the same function that we used in the previous step.

What we just did:

  • We used fetch() to retrieve the json at this address: FIREBASE_JSON
  • We manipulated the response of fetch(), using then(), in something that we can use
  • We isolated the first post and displayed it in the page using drawElement()