Comments not Displaying Under Posts - Handlebars.js and Express.js

56 Views Asked by At

I'm working on a web application where users can post and comment on posts. I'm using Handlebars.js for rendering on the client-side and Express.js on the server-side. However, I'm facing an issue where comments are not being displayed correctly under posts.

Despite confirming that comments data is successfully retrieved from the server and logged, and that Handlebars templates are set up correctly, comments are still not displaying under posts as expected.

I've gone through several debugging steps, including checking the data retrieval, client-side JavaScript, Handlebars templates, CSS, and even server logs, but I haven't been able to identify the root cause.

commentRoutes.js file:

router.get('/', async (req, res) => {
  try {
    const commentData = await Comment.findAll({
      attributes: ['id', 'comment_text', 'user_id', 'post_id', 'created_at'],
      order: [['created_at', 'DESC']],
      include: [
        {
          model: User,
          attributes: ['username'],
        },
      ],
    });
    console.log('Comments Data:', commentData);
    res.status(200).json(commentData);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error });
  }
});

comments.handlebars file:

{{log post}}
<div class="comments">
    {{#each this}}
    <div class="comment">
        <p>{{user.username}} on {{format_date created_at}}</p>
        <div class="text">{{comment_text}}</div>
    </div>
    {{/each}}
</div>

post.handlebars file:

{{> post-info post}}

{{#if loggedIn}}
<form class="comment-form">
    <div class="comment-container">
        <label for="comment-body">Leave a comment:</label>
        <textarea name="comment-body"></textarea>
        <button class="button add-comment-btn" type="submit">Add Comment</button>
    </div>
</form>
{{/if}}


{{> comments post.comments}}

{{#if loggedIn}}
<script src="/js/comment.js"></script>
{{/if}}

comment.js file:

const commentFormHandler = async function (event) {
  event.preventDefault();

  // Extract post_id from the current URL
  const post_id = window.location.toString().split('/')[
    window.location.toString().split('/').length - 1
  ];

  // Get comment text from the textarea
  const comment_text = document
    .querySelector('textarea[name="comment-body"]')
    .value.trim();

  // Check if comment text is not empty
  if (comment_text) {
    try {
      // Send a POST request to create a new comment
      const response = await fetch('/api/comments', {
        method: 'POST',
        body: JSON.stringify({
          post_id,
          comment_text,
        }),
        headers: {
          'Content-Type': 'application/json',
        },
      });

      // Check if the response is successful
      if (response.ok) {
        // Reload the page to display the new comment
        document.location.reload();
        console.log('Comment created successfully!');
      } else {
        // Display an alert with the error message if unsuccessful
        alert('Failed to create comment');
      }
    } catch (error) {
      // Log any unexpected errors to the console
      console.error('Error creating comment:', error);
      // Display an alert for unexpected errors
      alert('Failed to create comment');
    }
  }
};

// Attach the commentFormHandler to the button's click event
document
  .querySelector('.add-comment-btn')
  .addEventListener('click', commentFormHandler);
0

There are 0 best solutions below