You are viewing a single comment's thread. Return to all comments →
I have used one of the most useful array method reduce, to solve this problem.
import React, { useState } from "react";
const ASPECTS = ["Redability", "Performence", "Security", "Documentation", "Testing"];
const FeedbackSystem = () => {
const [votes, setVotes] = useState( ASPECTS.reduce((acc, aspect) => ({ ...acc, [aspect.toLowerCase()]: {upvote: 0, downvote: 0} }), {}) );
const handleUpvote = (aspectName) => { const key = aspectName.toLowerCase(); setVotes((prevVotes) => ({ ...prevVotes, [key]: { ...prevVotes[key], upvote: prevVotes[key].upvote + 1 } })) }
const handleDownvote = (aspectName) => { const key = aspectName.toLowerCase(); setVotes((prevVotes) => ({ ...prevVotes, [key]: { ...prevVotes[key], downvote: prevVotes[key].downvote + 1 } })) }
return ( { ASPECTS.map((item, idx) => (
export default FeedbackSystem;
Seems like cookies are disabled on this browser, please enable them to open this website
Code Review Feedback
You are viewing a single comment's thread. Return to all comments →
I have used one of the most useful array method reduce, to solve this problem.
import React, { useState } from "react";
const ASPECTS = ["Redability", "Performence", "Security", "Documentation", "Testing"];
const FeedbackSystem = () => {
const [votes, setVotes] = useState( ASPECTS.reduce((acc, aspect) => ({ ...acc, [aspect.toLowerCase()]: {upvote: 0, downvote: 0} }), {}) );
const handleUpvote = (aspectName) => { const key = aspectName.toLowerCase(); setVotes((prevVotes) => ({ ...prevVotes, [key]: { ...prevVotes[key], upvote: prevVotes[key].upvote + 1 } })) }
const handleDownvote = (aspectName) => { const key = aspectName.toLowerCase(); setVotes((prevVotes) => ({ ...prevVotes, [key]: { ...prevVotes[key], downvote: prevVotes[key].downvote + 1 } })) }
return ( { ASPECTS.map((item, idx) => (
{item}
upvote-btn-{idx}} onClick={() => handleDownvote(item)}> 👎 Downvote upvote-count-${idx}}> Upvotes: {votes[item.toLowerCase()].upvote} downvote-count-${idx}}> Downvotes: {votes[item.toLowerCase()].downvote} )) } ); };export default FeedbackSystem;