(Part 5)Tutorial On Steem/SteemConnect JS Retrieve And Comment The Last Post @steemconnect pt5

in #utopian-io6 years ago

Repository

https://github.com/igormuba/steemhere/tree/class5
I am making new branches according to the class

What Will I Learn?

We have already learned how to make a post to the blockchain, now we will learn

  • steem.js library: Retrieve the last post by user
  • steemconnect JavaScript library Make a comment on a post
  • DOM manipulation (AKA magic): Only show the comment field after posting

Requirements

It is recommended that you have followed the last tutorials to understand what are we doing (links on the bottom of the page), sels you need

  • Basic JSON knowledge
  • Basic HTML knowledge
  • Intermediate JavaScript knowledge
  • Steem account
  • SteemConnect app

Difficulty

  • Intermediate

Tutorial Contents

My motivation for this series:

I have started this series because of my frustration with the lack of tutorials and learning materials to work with the Steem and SteemConnect API. The documentation they have is NOT beginner friendly and very intimidating. My goal is to make things as simple and beginner friendly as possible, and even copy and paste friendly if possible.
I hope someday a better developer than me see this tutorials and take his time to make his own and better tutorials (or if lacks time contact me and help in this series), or even Steem/SteemConnect team realize their API documentation and tutorials are not very beginner friendly

Previously

We will follow up with the SteemConnect API, previously we have tweaked the comment function to make a post, but now we will also start using the Steem JavaScript library to add more functionality and flexibility. The SteemConnect API is useful for posting and doing things that require your authorization, but when you just need to retrieve posts or data that are publicly available you can use the Steem JS library itself since it does not require authentication.

New JavaScript file

I am creating a new file called myscript5.js inside the JS folder of the project of this classes, we could make everything on the old JavaScript file but after I finished the testings for this class I have realized that the code was too big, so I have started again putting all the new content on this new file and trying to make it cleaner than the old one, which still has the functions of the old tutorials

Importing Steem JS library and the new JS file

<script src="js/myscript5.js"></script> 


<script src="https://cdn.steemjs.com/lib/latest/steem.min.js"></script>

You can read more about on their github
https://github.com/steemit/steem-js/tree/master/doc

Getting the last post by author

This is the function to get the last posts by the author
steem.api.getDiscussionsByAuthorBeforeDate(author, permlink, date, max, function(err, result){}

I will add it into the old myscript.js file so we can use the variables we have already used to make things simple, I want you to understand the function itself, not lose time starting again what we have already done.

So, previously we have put on the myscript.js file the function from the SteemConnect API
api.comment("", parentPermlink, author, permlink, title, body, jsonMetadata, function (err, res) to make a post, not a comment, right below that we will use the other API, the Steem API.


So do as following:

  steem.api.getDiscussionsByAuthorBeforeDate(author, permlink, '2019-05-01T00:00:00', 1, function(err, result) {
  document.getElementById("retrievedPost").innerHTML = result["0"].body;
  document.getElementById("retrievedTitle").innerHTML = result["0"].root_title;

  document.getElementById("commentElement").innerHTML = `
    Content <textarea id="commentContent"></textarea><br>
    <input type="button" value="Post Comment!" onclick="submitComment()">
  `;

  });

Did you notice a few things?
document.getElementById("retrievedPost")
and
document.getElementById("retrievedTitle")

They are there so we can change an HTML element to the text we retrieved from the blockchain.
So, let us jump into the index.html file and add them there before I explain the rest

You simply need to add

  <h1 id="retrievedTitle">title</h1>
    <p id="retrievedPost">post</p>

Now, back to the JavaScript, I will show you the structure of the JSON element we have received and is stored in the object result

But the only things we want here are the body and the title. I will show you how to get it and depending on your application you can use the same pattern to get other elements!
result["0"].InsertHereWhatYouWant;
In our case we want the body and the title, this is why we have put on the code above .body and .title

If you want to see all the elements of the json, put inside the function a console.log, on the example below I am hard coding my username and no permlink to get the very very last post just to show you what to do to see the data structre of the JSON, this will print the last post on the console

steem.api.getDiscussionsByAuthorBeforeDate("igormuba", "", '2019-05-01T00:00:00', 1, function(err, result){
console.log(result);
});

DOM manipulation to hide/show elements

Moving on, the next thing from the screenshot/chunk of code I want to explain is

Here we are using JavaScript to make a very fancy DOM manipulation, it looks like we are coding HTML inside the JavaScript file, right?

What this does is:
After we have retrieved the last post, only then we will show the "post comment field", this is fancy (though my presentation is ugly) but it is important to keep in mind we can do this to remove from the page unnecessary content, I thought it would be a neat trick to show you. You can do this for many chunks of code but here we are keeping things simple.

Submiting the comment

Now that we have added the code to retrieve the last post, understood it and displayed the make comment HTML content to the user is time to make our own comment, the final code will look like

But as Mr. Hannibal would say, "let us separate it into parts"

First we are declaring a function called submitComment(), inside it:

First, we are giving a title to the comment by just adding "re ", to mean reply, to the comment, most interfaces won't even show this

var commentTitle = title=document.getElementById("title").value;
  commentTitle = "re "+commentTitle;

Now, we are getting the comment content from the HTML chunk of code we have magically put inside a JavaScript, that one that only shows after we have posted and retrieved the post

var commentContent = document.getElementById("commentContent").value;

Now, we are flexing our JavaScript muscles to get the the title from the HTML, that we have filled 1 class ago, to turn it into the parent permLink

var parentPermlink= document.getElementById("retrievedTitle").innerHTML;
  parentPermlink = parentPermlink.replace(/ /g, "-");
  parentPermlink = parentPermlink.toLowerCase();

The author we also get from the HTML that we have filled 2 classes back

var author=document.getElementById("username").innerHTML;

We are also using the parent permLink to generate the answer permlink by just adding "re-" before the parent link

var permLink = "re-"+parentPermlink;

Now we just use the comment function we have used in the other tutorial to make a post, but previously we have tweaked it to make full posts, now we are filling the parameters to make a real comment inside a real post

api.comment(author, parentPermlink, author, permLink, "", commentContent, "", function (err, res)

So, now, if you jump into the index.html you should be able to

  • make a post
  • see the post on your screen
  • the DOM magic will make the comment field appear
  • fill the field and make a comment

Curriculum

Proof of Work Done

index.html
https://github.com/igormuba/steemhere/blob/class5/index.html

myscript.js
https://github.com/igormuba/steemhere/blob/class5/js/myscript.js

myscript5.js
https://github.com/igormuba/steemhere/blob/class5/js/myscript5.js

Hey, I am Witness, did you know?

To vote for me, simple 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.

  • This looks like somewhat of an improvement over the past work.
  • Your scripts are still not in the head section of your HTML, actually i did not spot a head section, again how come? :)
  • Showing the post structure could be not enough for users. You could point them the official Steem documentation here which explains every single field
  • Adding few more screenshots (or a gif) of how the comment will show after the action would have also been an added value
  • Why are you using root_title instead of title to grab the post title? I think using title makes more sense. Check out documentation link above ;)
  • You actually are now using SteemJS alongside steemconnect, while before you used dsteem. Any reason for this move? keep in mind that dsteem is now the favorable Steem library.

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]

Hi, thank you very much for the thoughtful feedback and I am very happy to read it is "somewhat of an improvement"\n\nI am using Steem because the initial idea from the very first tutorial was to cover Steem/Dsteem and SteemConnect, there is not specific reason why I decided to cover steem.js first, I am doing a solo project related to messaging on Steem and I was using this library so this came to my mind first, but I hope to cover all 3 on the end so people searching for any of them will find content.\n\nThe GIF idea is actually very very good, I will possibly try to explore this on the next one as I plan to cover more front end and other content alongside with the API classes so readers can learn or at least know what a bit more to help them make their applications

Posted using Partiko Android

Thank you for your review, @mcfarhat! 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

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!

Hi, and thanks for the tuts. I stumbled upon your post today while trying to build my own webapp using SteemConnect but with React.

So far so good, I can vote using my webapp. The only problem I'm having is trying to post a comment. To be precise, I don't intend to make a new post, all I want to do is make a comment on an existing post. Every time I'm trying to use the api.comment function, it's returning me with a cryptic 401 error.

I've consulted the steemconnect documentation here https://www.npmjs.com/package/steemconnect which is absolutely terrible since it doesn't explain anything at all on the needed parameters.

So, I'm really asking you if you can help me here and clarify the parameters I need? (An example response e.g) I'll appreciate it.

Here's the function in question:
api.comment(parentAuthor, parentPermlink, author, permlink, title, body, jsonMetadata, function (err, res) {
console.log(err, res)
});

Do I need all of the parameters for a simple comment? I see that you passed author twice, and skipped on a few, and to be honest, I'm quite confused by what you're doing.

Anyway, thanks in advance. I'm really looking forward to solving this.

Hi! I am sorry if it was not clear to you. I completely agree with you that the documentation is really poor and not very helpful! Seems like every developer develop their workarounds for the lack of information.
The complete function to post a comment is:

api.comment(parentAuthor, parentPermlink, author, permlink, title, body, jsonMetadata, function (err, res) {
  console.log(err, res)
});

I have inserted author twice because I knew I was going to comment my own post since I was the only one using the testing platform. Now that I look back I realize it was bad for the didactics.

The parameters that I left blank with "" are jsonMetadata and title.
jsonMetadata: Is extra data that won't be used by Steemit or blogging, but are useful for other applications, such as SteemMonsters. It is a piece of JSON code that is stored but not executed by default by the Steem nodes, only by the applications/nodes that are actually looking to execute that in that context.
title: comments on Steemit don't need a title, only posts do, so I skipped that

The full implementation of that piece of code from this class is:
https://github.com/igormuba/steemhere/blob/class5/js/myscript5.js

Hello and thanks for the reply, I've ran your code and it actually works. But I've copied and pasted the same piece of code in mine, and strangely, I'm still getting a sc2-sdk null error.

Frankly, I'm quite baffled by what's going on. Here's my arrow function, and the data I've inputted.


submitComment = () => {

SteemConnect.comment("eaudebla", "crowthelegendvrreview-mdnmolwle9", "eaudebla", "re-crowthelegendvrreview-mdnmolwle9", "", "this is a test", "", function (err, res) {
console.log(err, res);
});

}

I

The function seems right. Did you initialize and log into SteemConnect?
The code for that is here
https://github.com/igormuba/steemhere/blob/class5/js/myscript.js
I empalia that on the previous tutorials, but maybe my didactics were not good enough at that time.
Also, make sure you have the package with the dependencies set
https://github.com/igormuba/steemhere/blob/class5/package.json

Yes, I already logged on steemconnect. I also have the dependencies installed. I’m going to upload my code on GitHub so maybe someone can have a look. Sorry to disturb, but I’m literally losing sleep over this. If you know anyone else who has worked on steemconnect, let me know. The scarcity of people using it is a problem.

EDIT: Here's my code in question
https://github.com/ChilledMatter/AkibaSteem

My comment function is under https://github.com/ChilledMatter/AkibaSteem/blob/master/src/components/PostDetail.js

This is really strange. I have got similar problem as only api.me function works. When I am trying to vote or post a comment I get 401 response...

The guy over at steemconnect's github page managed to fix it!

Just authorize your app here.

https://app.steemconnect.com/authorize/@steemconnect

Coin Marketplace

STEEM 0.18
TRX 0.15
JST 0.030
BTC 58776.30
ETH 2576.56
USDT 1.00
SBD 2.44