(Part 7) Steem JavaScript API Tutorial - Fetch And Display A Real Feed pt7

in #utopian-io6 years ago

Repository

https://github.com/igormuba/Steem-Feed-Example-

What Will I Learn?

  • Create a query
  • Fetch the feed from a user
  • DOM manipulation to formate and display
  • Convert markup to HTML

Requirements

  • Internet connection
  • Code editor
  • Browser
  • Reading the previous classes is recommended but not necessary

Difficulty

  • Intermediate

Tutorial Contents

From now on I believe we have covered the basics of JavaScript/Steem API interaction, so it is time to move to a more "practical" (read user interface) side of things.

We have been simply working with 1 post and 1 comment, but it is time to get more advanced from now on.

The Index

The index file will simply host the shadow paragraph tags for us to DOM manipulate in the script, they are just hosts for the post content, so there is not much else to do here other than creating 3 paragraph tags with IDs 1 through 3 and importing the Steem script

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    <script src="https://cdn.steemjs.com/lib/latest/steem.min.js"></script>
    
</head>
<body>

<p id="1"></p>
<p id="2"></p>
<p id="3"></p>
<script src="js/myscript.js"></script>
</body>
</html>

Creating the query

The function from the Steem library we are going to use is

steem.api.getDiscussionsByFeed(query, function (err, result){}

So we need to build a query with the author and how many posts we want to fetch, I hope that by now you are comfortable with objects/JSON and arrays

The tag is the user where we will fetch the feed from, and the limit is how many posts we will get from his feed, in this case, I want just 3 posts for demo purposes.

So, in the example below I am looking for the 3 last posts (limit: 3) from the user me, that is igormuba (tag: 'igormuba',)

// change the tag to your own username to see if it works later
let query = {
    tag: 'igormuba',
    limit: 3
}

What do the function returns

Before we touch on what do we get in return, let us console.log the result, please, use your browser to also see all the content that is returned from each post.

If you want a cleaner result you can go back and change the limit to 1 post.

let query = {
    tag: 'igormuba',
    limit: 1
}

But don't forget to go back to 3 later, or how many posts you want to get, and don't forget you also need the same amount of P tags with the IDs set too

loggin to the console

steem.api.getDiscussionsByFeed(query, function (err, result) {
console.log(err, result);
}

Will return a JSON file with the posts we want

In this case, I am getting the last 3 posts from my own feed.

NOTE: This is not my last 3 posts, it is the last 3 posts that are fed into me, like the timeline of content I see, not the content I post, though I believe if I post and my post is in the last 3 things on my feed it will appear here too

Building the posts

I thought of a few ways we could build the posts, but I have decided to use a for loop to iterate through the posts we have fetched and fill them inside the paragraph tags.

This seemed like the fastest and easiest way to just demo the DOM manipulation to fill the elements returned from the blockchain.

for (let i=0; i<result.length; i++){

}

Now, if you did like me and name the <p> tags IDs 1 to 3, then we can use the i from the loop to find the right paragraph from the right post by adding 1 to it and converting to string.

Remember: arrays start counting from 0, but I am counting the P tags from 1, now that I think about it it is dumb but it is not such a huge thing, just do as follows and you won't ever worry about it again

for (let i=0; i<result.length; i++){
let iToString = (i+1).toString();
}

Manipulating the DOM to add the posts

Now it is just a matter of DOM manipulation to add the posts in a formatted way.

If in the last sections you have used the console.log to see what JSON properties you get back from the call, you might have other properties you might want to add, such as images, how much money did the post make, etc, but to keep it simple I am using just what really matters for a post, in order:

  1. The title
  2. The author
  3. The body
document.getElementById(iToString).innerHTML = `
        <h1>`+result[i].title+`</h1>
        <h2>`+result[i].author+`</h2>
        <p>`+result[i].body+`</p>
        <hr>
        `

This will create an H1 tag with the title, an H2 tag with the author and a P tag with the body.
And as our code iterating through the results it will fill in the right order, let us see?

The results

The code looks like this

And my feed looks like this

And now the moment of truth!
Open the index.html file and see if it works, we expect to see the same posts in the same order...

And we do!

I hope you could replicate step by step and see the same results.

One more thing

If you have repeated the steps you might have noted that the markdown tags are ugly, they are not being displayed as proper HTML.

We can use a library called ShowDown to change markdown to HTML automatically. Check their github below for more info, this is very helpful
https://github.com/showdownjs/showdown

So, let us import to our html

<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script>

And on our code
Before the document.getElementById(iToString).innerHTML do the following

let converter = new showdown.Converter()
let text = result[i].body
let html = converter.makeHtml(text);

And the P inside our DOM manipulation now is <p>+html+</p>

So altogether:

steem.api.getDiscussionsByFeed(query, function (err, result) {
    console.log(err, result);
    for (let i=0; i<result.length; i++) {
        let iToString = (i+1).toString();
        let converter = new showdown.Converter()
        let text = result[i].body
        let html = converter.makeHtml(text);
        document.getElementById(iToString).innerHTML = `
        <h1>`+result[i].title+`</h1>
        <h2>`+result[i].author+`</h2>
        <p>`+html+`</p>
        <hr>
        `
    }
  });

And now the images, links, etc, all appear as normal, either the author has created them in HTML markup or in markdown

Curriculum

I AM A STEEM WITNESS

To vote for me, simply use the SteemConnect link below
https://steemconnect.com/sign/account-witness-vote?witness=igormuba&approve=1

or go to https://steemit.com/~witnesses

(note, it is /~witnesses, not /witness)
Scroll all the way down to "If you would like to vote for a witness outside of the top 100, enter the account name below to cast a vote."

type igormuba and click vote

Sort:  

Thank you for your contribution @igormuba.
After an analysis of your tutorial we suggest the following points:

  • Always include comments in the code sections, as it helps users a lot to better understand what they are developing.

  • The functions that you exemplify in your tutorial are already well documented, but in your tutorial it became interesting with examples in practice.

Good job and very interesting for those who do not quite understand the STEEM API.
Continuation of a good work in the development of tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @igormuba!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

I am learning steemit api. Your lecture is very helpful

Posted using Partiko iOS

Hey, @igormuba!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.20
TRX 0.13
JST 0.030
BTC 66408.50
ETH 3486.20
USDT 1.00
SBD 2.70