I just want to create a simple component as a Like button. The usage is simple, if the user hits the button his/her username is added to the list (a string) in order to verify this. If hits again the button, his/her username is removed from the string.
import React, { useContext, useEffect, useState } from 'react';
import classnames from 'classnames';
import HeartLike from '../../svg/HearLike/HeartLike';
import { updatePostLike } from '../../api/post';
import './PostShare.css';
const PostShare = ({likedUsers, id}) => {
const [totalLikedUsers, setTotalLikedUsers] = useState("User 1; User 2;");
const user = {username: "User 2"};
useEffect(() => {
async function updateLike(likedData) {
const response = await updatePostLike({liked: likedData}, id);
}
//save to database
updateLike(totalLikedUsers);
}, [totalLikedUsers])
return (
<div className="post-share">
<p onClick={() => {
totalLikedUsers.includes(user.username)
? setTotalLikedUsers(likedUsers.replace(user.username + ";", ""))
: setTotalLikedUsers(likedUsers + user.username + ";")
}}><HeartLike /></p>
</div>
);
}
export default PostShare;
With this code, the components starts with the variable totalLikedUsers set to:
"User 1;User 2;"
If User 2 hits de like button, her/his username will be removed:
"User 1;"
But if he/she hits again the button and updating the variable with setTotalLikedUsers, the result is that is added twice when it should only add once:
"User 1;User 2;User 2;"
I have been trying to understand what is happening and I cannot find a solution.