I have a like system similar to Instagram. The problem's that whenever I like a photo, the currentUserClicks state isn't its own state to all users
For example: There exists photos A and B. A has 10 likes B has 20 likes.
If I click like on photo A, then the like count correctly becomes 11
Right after, if I click like on photo B, then the like count incorrectly becomes 19 instead of 21
The currentUserClicks state thinks that photo B should be disliked (decrement the like count by 1 just like Instagram) because currentUserClicks becomes >= 1.
How can I make it so that each user has its own currentUserClicks value?
const [currentUserClicks, setCurrentUserClicks] = useState(null);
const handleLikesBasedOnUserId = (likedPhotoUserId) => {
if(currentUserClicks >= 1) {
setCurrentUserClicks(currentUserClicks - 1);
handleDislike(likedPhotoUserId);
} else {
setCurrentUserClicks(currentUserClicks + 1);
handleLike(likedPhotoUserId);
}
};
You can "individualize" state in a couple basic ways.
Push the state down to the components it pertains to.
Here you move the currentUserClicks state into a React component that manages its own state and updates, completely independent of any other React component.
Example:
const InstagramPost = (props) => {
const [liked, setLiked] = useState(false);
const handleLikesBasedOnUserId = () => {
if (liked) {
handleDislike(id); // id from props
} else {
handleLike(id);
}
setCurrentUserClicks(liked => !liked);
};
...
return (
...
<button onClick={handleLikesBasedOnUserId}>like</button>
...
);
};
...
{posts.map(post => (
<InstagramPost key={post.id} ....props.... />
))}
Lift the state up to a common ancestor component and handle merging state updates.
Example:
const InstagramPost = ({ liked, likeHandler }) => {
...
return (
...
<button onClick={likeHandler}>like</button>
...
);
};
...
const [liked, setLiked] = useState({});
const handleLikesBasedOnUserId = (id) => {
if (liked[id]) {
handleDislike(id);
} else {
handleLike(id);
}
setCurrentUserClicks(liked => ({
...liked,
[id]: !liked[id], // toggle liked state by id
}));
};
...
{posts.map(post => (
<InstagramPost
key={post.id}
liked={liked[post.id]}
likeHandler={() => handleLikesBasedOnUserId(post.id)}
....props....
/>
))}