22
33import { useEffect , useState } from "react" ;
44import { useUserStore } from "@/store/codev-store" ;
5+ import { useFeedsStore } from "@/store/feeds-store" ;
56import { ArrowBigUp } from "lucide-react" ;
67
78import {
89 AddPostUpvote ,
10+ countUpvotes ,
911 hasUserUpvoted ,
1012 removePostUpvote ,
1113} from "../_services/action" ;
@@ -19,7 +21,11 @@ export default function PostUpvote({ post }: PostUpvoteProps) {
1921 const { user } = useUserStore ( ) ;
2022
2123 const [ isUpvoted , setIsUpvoted ] = useState ( false ) ;
22- const [ upvotes , setUpvotes ] = useState ( post . upvoters_id ?. length || 0 ) ;
24+ const [ upvotes , setUpvotes ] = useState ( 0 ) ;
25+ const { posts, fetchPosts } = useFeedsStore ( ( state ) => ( {
26+ posts : state . posts ,
27+ fetchPosts : state . fetchPosts ,
28+ } ) ) ;
2329
2430 useEffect ( ( ) => {
2531 const checkUpvote = async ( ) => {
@@ -34,33 +40,43 @@ export default function PostUpvote({ post }: PostUpvoteProps) {
3440 } else {
3541 setIsUpvoted ( false ) ;
3642 }
37- } ;
3843
44+ if ( post ?. id ) {
45+ try {
46+ const upvotesCount = await countUpvotes ( post . id ) ;
47+ setUpvotes ( upvotesCount ) ;
48+ } catch ( error ) {
49+ console . error ( "Error counting upvotes:" , error ) ;
50+ }
51+ }
52+ } ;
3953 checkUpvote ( ) ;
40- } , [ user ?. id , post ?. id ] ) ;
54+ } , [ user ?. id , post ?. id , posts ] ) ;
4155
42- const handleUpvote = ( e : React . MouseEvent ) => {
56+ const handleUpvote = async ( e : React . MouseEvent ) => {
4357 if ( user ) {
4458 e . stopPropagation ( ) ;
4559 e . preventDefault ( ) ;
4660
61+ setIsUpvoted ( ( prev ) => ! prev ) ;
62+ setUpvotes ( ( prev ) => prev + ( isUpvoted ? - 1 : 1 ) ) ;
63+
4764 if ( ! isUpvoted ) {
48- AddPostUpvote ( post . id , user . id ) ;
65+ const postUpvote = await AddPostUpvote ( post . id , user . id ) ;
4966 } else {
50- removePostUpvote ( post . id , user . id ) ;
67+ await removePostUpvote ( post . id , user . id ) ;
5168 }
5269
53- setIsUpvoted ( ( prev ) => ! prev ) ;
54- setUpvotes ( ( prev ) => prev + ( isUpvoted ? - 1 : 1 ) ) ;
70+ await fetchPosts ( ) ;
5571 }
5672 } ;
5773
5874 return (
5975 < button
6076 className = { `flex items-center space-x-1 ${
6177 isUpvoted
62- ? "text-customBlue-500 dark:text-customBlue-400 "
63- : "hover:text-customBlue-500 dark:hover:text-customBlue-400 "
78+ ? "text-customBlue-300 dark:text-customBlue-200 "
79+ : "hover:text-customBlue-300 dark:hover:text-customBlue-200 "
6480 } `}
6581 onClick = { handleUpvote }
6682 >
0 commit comments