Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.9 kB
4
Indexable
Never
import React, { useState, useEffect } from 'react';
import { useParams,Link } from 'react-router-dom';
import axios from 'axios';
import './CommentsPage.css'
 
const CommentsPage = () => {
  const { title } = useParams();
  const [comments, setComments] = useState([]);
 
  useEffect(() => {
    fetchComments();
  }, []);
 
  const fetchComments = async () => {
    try {
const response = await axios.get(`http://localhost:5221/api/Blog/GetComments?t=${encodeURIComponent(title)}`);
      const data = response.data;
      setComments(data);
    } catch (error) {
      console.error('Error fetching comments:', error);
    }
  };

  const handleDeleteComment=async(userName)=>{
    try {
        await axios.delete(`http://localhost:5221/api/Blog/comments?Blogtitle=${encodeURIComponent(title)}&username=${encodeURIComponent(userName)}`);
              
              // After deletion, fetch the updated comments
              fetchComments();
            } catch (error) {
              console.error('Error deleting comment:', error);
            }
  }
 
  return (
    <div className="full3">
      <div className="comments-container">
        <Link to={`/blog/${title}`} className="backbutton">
          Back
        </Link>
        <h2>Comments for {title}</h2>
        {Object.keys(comments).map((commentKey) => (
          <div key={commentKey} className="comment-box">
            <p><strong>Rating:</strong> {comments[commentKey].rating}</p>
            <p><strong>Review:</strong> {comments[commentKey].review}</p>
            <p><strong>Username:</strong> {comments[commentKey].userName}</p>
            <button className="deleteButton" onClick={()=>handleDeleteComment(comments.userName)}>Delete</button>
          </div>
        ))}
      </div>
    </div>
  );
};
 
export default CommentsPage;
Leave a Comment