#Working with JSON data for interactive comments section

162 messages · Page 1 of 1 (latest)

brazen badge
vivid gulch
#

Ah well ik it’s the basics I’m just trying to programmatically display the content using the JSON data

#

Does using the ID’s make sense ?

brazen badge
#

yes, use ID to "link" the data to the UI.

vivid gulch
#

my heads a jumbled mess thinking of how to solve this. Is the ID value a good idea or is there a better way to do this ?

brazen badge
#

I answered that already

#

show what you've tried

vivid gulch
#

honestly, idk where to begin

#

use map method on comments, then check to see if the id's match between html and comment data ?

#

if the id's match, then populate data, and increase value of id by 1 ?

brazen badge
#

you don't "increase value of id". if you're using .map(), you are using all IDs. again, show some code if you want help.

#

if you can't even get started, refer to my first reply above.

vivid gulch
#

I meant the id value in the html

#

I will send the code in a bit, not next to my desk atm

vivid gulch
#

i got it to work (kinda)

#

not all the way, but I'll see how far i get, and message here if im not able to solve it

#

thanks for the nudge in the right direction, though

vivid gulch
#

alright actually ive run into a bit of an issue

#

😅

#

@brazen badge

brazen badge
#

On mobile. Will look in a few

vivid gulch
#

copy

vivid gulch
#

pretty sure it could be the 79th line

brazen badge
#
let comments = data.comments.map((comment) => comment);

😢

const { comments } = data;

👌🏼

#

don't use .insertAdjacentHTML() or giant HTML strings. use HTML templates and/or createElement() and append()

vivid gulch
#

wait hold on

brazen badge
#

you are using .map() for no reason...

#

returning each item exactly as-is, so you return the same array

vivid gulch
#

it gets rid of the current user object though

brazen badge
#

what?

#

no, the map doesn't

vivid gulch
#

ohhh right

#

tried using append

#

but it doesnt work because html isnt of node type

#

wouldnt it just be easier to use the HTML string since its alot to insert ?

vivid gulch
#

oh i get it, store it into a template, copy it, and select for certain things to change

vivid gulch
#

hey, having some trouble between lines 41 and 47. trying to set the class to "reply-container" when the username = juliusomo and else 'reply-btn-container'

#

not sure how to do that here

brazen badge
#

Show those lines. F replit

#
    if (comment.user.username === "juliusomo") {
      copyTemplate
        .querySelector(".reply-container")
        .classlist.add("reply-btn-container");
    } else {
        .classlist.add("reply-btn-container")
    }

you're calling .classlist on nothing in the else. it's also, .classList

#

(and you're adding the exact same class in both cases)

#
const replyClass = comment.user.username === "juliusomo" ? "reply-btn-container" : "something-else-container";
copyTemplate.querySelector('.reply-container').classList.add(replyClass);
vivid gulch
#

Sorry if I ended up pinging you more than once, my discord is acting up

#

ohhh i see

#

thank you

vivid gulch
vivid gulch
#

https://replit.com/@Mohammedmiah02/Interactive-Comments-Section trying to get rid of the reply, edit and delete button based off the username being juliusomo. I used the dev tools and its placing the "reply-btn" and "modal-display" together. Im assuming this is happening because I didnt use classList.add and classList.remove ? Lines 45-71.

Mohammedmiah02

Run HTML, CSS, JS code live in your browser. Write and run code in 50+ languages online with Replit, a powerful IDE, compiler, & interpreter.

brazen badge
#

please start showing the relevant code here instead of making us look at Replit's garbage site.

    const replyContainer =
      comment.user.username === "juliusomo"
        ? "reply-container"
        : "reply-btn-container";
    copyTemplate
      .querySelector(".reply-container")
      .classList.add(replyContainer);

    //setting display of reply button based off username
    const replyButton =
      comment.user.username != "juliusomo" ? "reply-btn" : "modal-display";
    copyTemplate.querySelector(".reply-btn").classList.add(replyButton);
          <div class="reply-container">
            <button class="btn reply-btn">
              <img class="reply-img" src="images/icon-reply.svg" />
              <p class="reply-text">Reply</p>
            </button>

            <button class="btn delete-comment-btn">
              <img class="del-img" src="images/icon-delete.svg" /> Delete
            </button>

            <button class="btn edit-comment-btn">
              <img class="edit-img" src="images/icon-edit.svg" /> Edit
            </button>
          </div>
#

NONE of the classes you're adding (.reply-btn, .modal-display, ``reply-container, and reply-btn-container`) even exist in your CSS...

vivid gulch
#

wym

#

theyre all there

#

in the css

#
  display: flex;
  align-items: center;
} ```

```.modal-display {
  display: none;
}```

.delete-comment-btn,
.edit-comment-btn,
.reply-container {
display: flex;
align-items: baseline;
}```

#

would i have to remove then add ?

vivid gulch
#

managed to fix i

#

it*

vivid gulch
#

having an issue here with my reply button where the image and button are coming out stacked on top of each other instead of side by side. This happened after i added in this piece of js code

 if (replyContainer) {
   if (comment.user.username === "juliusomo") {
     replyContainer.classList.add("reply-btn-container");
     replyContainer.classList.remove("reply-container");
   } else {
     const replyBtnContainer = copyTemplate.querySelector(
       ".reply-btn-container"
     );
     if (replyBtnContainer) {
       replyBtnContainer.classList.add("reply-container");
       replyBtnContainer.classList.remove("reply-btn-container");
     }
   }
 }```
https://replit.com/@Mohammedmiah02/Interactive-Comments-Section
Mohammedmiah02

Run HTML, CSS, JS code live in your browser. Write and run code in 50+ languages online with Replit, a powerful IDE, compiler, & interpreter.

brazen badge
#

what?

vivid gulch
#

reply button image and text are stacked on top of each other

#

this happened after i added in this piece of code:

    if (replyContainer) {
      if (comment.user.username === "juliusomo") {
        replyContainer.classList.add("reply-btn-container");
        replyContainer.classList.remove("reply-container");
      } else {
        const replyBtnContainer = copyTemplate.querySelector(
          ".reply-btn-container"
        );
        if (replyBtnContainer) {
          replyBtnContainer.classList.add("reply-container");
          replyBtnContainer.classList.remove("reply-btn-container");
        }
      }
    }```
#

tried turning on and off the flex display but its still the same

vivid gulch
#

@brazen badge

brazen badge
#

the style for .reply-btn does not exist?

#

has nothing to do with the container you're looking at. .reply-btn is the container holding the button/text

#

add display: flex to that and they're side-by-side:

vivid gulch
#
  display: flex;
  align-items: center;
}``` it does exist and the flex is already there
brazen badge
#

where do you see that? it's not in the CSS you posted

vivid gulch
#

ahhh

#

i see

#

its because i switch between the container classes in the js

#

so .reply-btn-container switches with .reply-container

#

above code only works when its .reply-btn.container

brazen badge
#

wow replit is absolute shit.. searching doesn't work at all

#

I'm not going to look at replit anymore. use a different service for further questions

vivid gulch
#

idk why it doesnt work for you cause i can shift+F and find it

#

i mean cmd+F

brazen badge
#

scroll to the top

#

doesn't work in chrome

vivid gulch
#

i am in chrome

#

i just tried and it works

#

try clicking on the css document itself and then cmd+F

vivid gulch
#

wondering if you could help me with this issue: I am trying to populate html elements which are comments where the value of the element are pulled from JSON data. Things like username, profile pic, etc are in the JSON data. The only thing is the JSON data is structured in a way where there is a comments array and within the comments array is a replies array filled with the data for the replies. I am trying to create a function that loops through both the comments array, including the replies and populates the elements using that data. I am having trouble with this line of code:

 comment.replies.forEach((reply) => {
   if (comment.user.username || comment.replies.user.username) {
     newElement.querySelector(".name").textContent = comment.user.username;
   }
 });```


This line is meant to loop through the replies array and grab the data from there, but I would also like it to loop through the comments array and also grab data from there too. I am just not sure how to go about doing that. The above code is also nested within a .forEach loop that goes loops over the comments as well.  This is my replit if you are confused: https://replit.com/@Mohammedmiah02/Interactive-Comments-Section#script.js
Mohammedmiah02

Run HTML, CSS, JS code live in your browser. Write and run code in 50+ languages online with Replit, a powerful IDE, compiler, & interpreter.

brazen badge
#

this code shows why frameworks are a thing 🙃

#

can you show an example of the JSON please?

vivid gulch
#

lmao, i mean yeah i havent delved into react yet

brazen badge
#

oh, i see it now

vivid gulch
#

you checked on the replit ?

brazen badge
#

ya, I see it. one sec. once you learn React you're going to cry. mapping through data is so easy 😄

vivid gulch
#

yeah my code look so long and pretty crazy

brazen badge
#

you're already doing comments.forEach()? I'm confused about what you're attempting to accomplish.

vivid gulch
#

comments.forEach() would iterate through the replies array as well ?

brazen badge
#

no, it iterates through comments. but each comment might have replies, so you loop through those inside the comments.forEach()

#

(prefer for..of to forEach() 😉 )

vivid gulch
#

okay so basically the code should iterate through the replies array in order to extract the data from it and apply it to the html elements

brazen badge
#
for (const comment of comments) {
  // do stuff with comment
  for (const reply of comment.replies) {
    // do stuff with replies
  }
}
vivid gulch
#

oh i put it within an external function

#

i did do that at first

#
function createAndPopulateNewElementFromTemplate(template, comment) {
  //importing template and grabbing content of template
  const newElement = document.importNode(template, true).content;

  //populating username
  comment.replies.forEach((reply) => {
    if (comment.user.username) {
      newElement.querySelector(".name").textContent = comment.user.username;
    } else if (comment.reply.user.username) {
      newElement.querySelector(".name").textContent =
        comment.reply.user.username;
    }
  });

  //adding 'user-self' class based off username
  //prettier-ignore
  const userSelfClass = comment.user.username === "juliusomo" ? "user-self" : "name";
  newElement.querySelector(".name").classList.add(userSelfClass);

  //adding time when comment was created
  newElement.querySelector(".time").textContent = comment.createdAt;

  //adding comment 'upvotes'
  newElement.querySelector(".upvote-num").textContent = comment.score;

  //populating user image
  newElement.querySelector(".profile-img").src = comment.user.image.png;

  //populating comment content
  newElement.querySelector(".comment-content").textContent = comment.content;

  return newElement;
}
#

Thats the function external to the loadfromJSONfunction() which has the comments.forEach loop

brazen badge
#

you probably need to be creating a new container element and then new child elements for each reply, then appending those to newElement

#

you're just looping through all the replies and assigning the data to the same element (replacing the previous reply)

vivid gulch
#

god this is confusing

#

i did have a different container(in terms of the html) for the replies themselves

brazen badge
#

everything I said still applies, but I guess that loop isn't to display the replies you're just using the username from the last reply if the comment itself doesn't have a username. weird, but okay. much more efficient method (uses first comment):

newElement.querySelector(".name").textContent = comment.username ?? comment.replies[0]?.user.username ?? 'Unknown';
vivid gulch
#

by that loop you're referring to this right:

    if (comment.user.username) {
      newElement.querySelector(".name").textContent = comment.user.username;
    } else if (comment.reply.user.username) {
      newElement.querySelector(".name").textContent =
        comment.reply.user.username;
    }
  });```
vivid gulch
vivid gulch
#

alright so i tried it a different way

#

last way was hard to follow

#

i am stuck

#

trying to work with the replies array and i dont exactly know what to do

#

i tried just following what was done for the comments object itself

#

this html template stuff is confusing

brazen badge
#

what are you trying to accomplish?

#

my god so much spaghetti

#

feel like I've told you this 100 times but you need to start reading the console

TypeError: Cannot destructure property 'comments' of 'data' as it is undefined.
vivid gulch
#

How is that spaghetti code ?

#

It’s pretty clearly defined

brazen badge
#

lines 30 and 118 are the only places you're destructuring comments from data. I'm far too lazy to unravel your spaghetti, but it's pretty clear that line 118 is the problem. In a function named repliesToHtml, you have this:

function repliesToHtml(comments, data) { // NOTE TWO PARAMETERS
  const {
    comments: { replies },
  } = data;

where you call repliesToHTML(), you're passing only a single argument which would be assigned to comments rather than data. so you're attempting to destructure undefined

#

why on earth is repliesToHtml reading either data or comments, though? the parameter you pass to that function should just be an array of replies

vivid gulch
#

i was thinking of not using the html template

#

shit is complicated

#

hold on man

#

bouta just use create element

vivid gulch
#

replyToHtml holds the structure of the comment including header, content, footer and then repliesToHtml maps the DOM tree to the HTML tree which actually creates the comment element itself hence why replies.map is applying a function

vivid gulch
brazen badge
#

Did you even read my reply?

vivid gulch
#

yes, did you read mine ?

#

how about you cut the condescension out

#

managed to fix it i think

brazen badge
#

you clearly didn't read my response if that's all you got out of it. you were attempting to destructure a variable that was not defined. you weren't using function parameters properly. it wasn't condescension, it was disbelief at your response seemingly completely ignoring the problem. you do you, though. I've had enough.

vivid gulch
#

lol most of your responses so far trying to 'help' me were pure condecension

#

"my god so much spaghetti"

#

"i answered that already"

#

you dont "increase value of id"

vivid gulch
vivid gulch
#

you seemed confused with what i was trying to do

#

I tried to clear that confusion.

brazen badge
#

I stand by that statement. your function is bad.

vivid gulch
#

see what i mean

#

'your function is bad'

#

no fucking shit

brazen badge
#

it's a fact. stop taking shit personally

vivid gulch
#

if you're trying to help, be constructive and ACTUALLY helpful

brazen badge
#

function takes input and provides output. your parameters make no sense and you aren't even using them (as I explained in detail)

#

and that's why I'm done. I bothered to dig into your code and told you exactly what you were doing wrong and now you're just whining. have a nice night...

vivid gulch
#

LOL and had you actually opened your eyes to read my replies you can see that I was clearing up YOUR confusion

#

NOT ignoring you

#

do better.

brazen badge
#

there is no confusion, buddy. your code is busted and I told you exactly how it's busted.

vivid gulch
#

you can code but you cant read ?

brazen badge
#

that was a rhetorical question. sorry that had to be pointed out, but it should have been obvious as I then went on to explain exactly why you should not be doing what you're doing

vivid gulch
#

and i explained in my response WHY i did what I did

brazen badge
#

...

vivid gulch
#

did you actually manage to read that response ?

#

or did YOU ignore MY response to your question

glacial ravine
#

Create a new forum post or ask in a help channel. This has been going for long and probably doesn't have anything to do with "Working with JSON data" anymore.
Put a minimal working sample and explain the expected output