• + 0 comments

    Solution:

    import React, { useState } from "react";
    const reviewTitle = ["Readability", "Performance", "Security", "Documentation", "Testing"];
    
    const FeedbackSystem = () => {
      const [upvoteCount, setUpVoteCount] = useState({});
      const [downVoteCount, setDownVoteCount] = useState({});
    
      const handleUpVote = (item, date) => {
        setUpVoteCount((prev) => {
          const prevVotes = prev[item]?.upvote || 0;
          return {
            ...prev,
            [item]: {
              upvote: prevVotes + 1,
              lastVotedAt: date,
            },
          };
        });
      };
    
      const handleDownVote = (item, date) => {
        setDownVoteCount((prev) => {
          const prevVotes = prev[item]?.downvote || 0;
          return {
            ...prev,
            [item]: {
              downvote: prevVotes + 1,
              lastVotedAt: date,
            },
          };
        });
      };
    
    
      return (
        <div className="my-0 mx-auto text-center w-mx-1200">
          <div className="flex wrap justify-content-center mt-30 gap-30">
            {reviewTitle && (
              reviewTitle?.map((item, index) => {
                return (
                  <div className="pa-10 w-300 card" key={item}>
                    <h2>{item}</h2>
                    <div className="flex my-30 mx-0 justify-content-around">
                      <button className="py-10 px-15" data-testid={`upvote-btn-${index}`}
                        onClick={() => handleUpVote(item, new Date().getTime())}>
                        👍 Upvote
                      </button>
                      <button className="py-10 px-15 danger" data-testid={`downvote-btn-${index}`} onClick={() => handleDownVote(item, new Date().getTime())}>
                        👎 Downvote
                      </button>
                    </div>
                    <p className="my-10 mx-0" data-testid={`upvote-count-${index}`}>
                      Upvotes: <strong>{upvoteCount?.[item]?.upvote || 0}</strong>
                    </p>
                    <p className="my-10 mx-0" data-testid={`downvote-count-${index}`}>
                      Downvotes: <strong>{downVoteCount?.[item]?.downvote || 0}</strong>
                    </p>
                  </div>
                )
              }))}
          </div>
        </div>
      );
    };
    
    export default FeedbackSystem;