I've been running into a problem with my react web application. In want to make a voting system where if you hit the like button it changes color and it can only be liked once. If you hit it again it goes back to 'neutral' and the like count gets decremented. Same goes for the dislike button. If you have something liked and you hit the dislike, for example, the the like goes back to eutral and the dislike changes color. Basically like the YouTube video like system. Im running into this problem, though, with my method:
const[score,setScore] = useState(0);
const[dislike,setDislike] = useState(0);
const[buttonState,setButtonState] = useState(true);
var boolD = true;
var boolL = true;
const incrmentLike = () => {
setScore(idea.score +=1)
console.log(idea.score)
}
var disliked = false;
const incrmentDislike = () => {
setDislike(idea.dislike +=1)
}
var flag = 0;
function toggleDislike(){
if(flag===0){
console.log(flag)
flag=1;
incrmentDislike()
console.log(flag)
disliked = true;
}
else if(flag===1){
setDislike(idea.dislike -=1)
disliked = false;
flag=0;
console.log(flag)
}
}
return(
<div className="idea-details">
{isPending && <div>Leading...</div>}
{idea && (
<article>
<h2>{idea.ideaTitle}</h2>
<p>Written by {idea.author}</p>
<div>{idea.body} </div>
<div>{idea.score} Likes {idea.dislike} Dislikes</div>
</article>
)}
<a type="button" className={classNameLU} id="button2" title="button" onClick={() => incrmentLike()}>Like!</a>
<div
className="btn btn-warning btn-lg"
style={{ backgroundColor: dislike ? "#35b5f1" : "#8b8b8b" }}
id="toggleDiv"
onClick={toggleDislike}
>
Dislike
</div>
</div>
);
} Basically The flag always gets reset to 0 and the method never gets to the if statement where the flag == 1. I think its because useState() is reseting the variable somehow. I was wondering if I could get help to get around this? I'm only working on the dislike button right now. setScore is the like button. You can ignore the first button.