@@ -9,11 +9,18 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
9
9
import { toast } from "react-hot-toast" ;
10
10
11
11
import LoadingSpinner from "./LoadingSpinner" ;
12
+ import { formatPostDate } from "../../utils/date" ;
12
13
13
14
const Post = ( { post } ) => {
14
15
const [ comment , setComment ] = useState ( "" ) ;
15
16
const { data : authUser } = useQuery ( { queryKey : [ "authUser" ] } ) ;
16
17
const queryClient = useQueryClient ( ) ;
18
+ const postOwner = post . user ;
19
+ const isLiked = post . likes . includes ( authUser . _id ) ;
20
+
21
+ const isMyPost = authUser . _id === post . user . _id ;
22
+
23
+ const formattedDate = formatPostDate ( post . createdAt ) ;
17
24
18
25
const { mutate : deletePost , isPending : isDeleting } = useMutation ( {
19
26
mutationFn : async ( ) => {
@@ -71,21 +78,44 @@ const Post = ({ post }) => {
71
78
} ,
72
79
} ) ;
73
80
74
- const postOwner = post . user ;
75
- const isLiked = post . likes . includes ( authUser . _id ) ;
76
-
77
- const isMyPost = authUser . _id === post . user . _id ;
78
-
79
- const formattedDate = "1h" ;
81
+ const { mutate : commentPost , isPending : isCommenting } = useMutation ( {
82
+ mutationFn : async ( ) => {
83
+ try {
84
+ const res = await fetch ( `/api/posts/comment/${ post . _id } ` , {
85
+ method : "POST" ,
86
+ headers : {
87
+ "Content-Type" : "application/json" ,
88
+ } ,
89
+ body : JSON . stringify ( { text : comment } ) ,
90
+ } ) ;
91
+ const data = await res . json ( ) ;
80
92
81
- const isCommenting = false ;
93
+ if ( ! res . ok ) {
94
+ throw new Error ( data . error || "Something went wrong" ) ;
95
+ }
96
+ return data ;
97
+ } catch ( error ) {
98
+ throw new Error ( error ) ;
99
+ }
100
+ } ,
101
+ onSuccess : ( ) => {
102
+ toast . success ( "Comment posted successfully" ) ;
103
+ setComment ( "" ) ;
104
+ queryClient . invalidateQueries ( { queryKey : [ "posts" ] } ) ;
105
+ } ,
106
+ onError : ( error ) => {
107
+ toast . error ( error . message ) ;
108
+ } ,
109
+ } ) ;
82
110
83
111
const handleDeletePost = ( ) => {
84
112
deletePost ( ) ;
85
113
} ;
86
114
87
115
const handlePostComment = ( e ) => {
88
116
e . preventDefault ( ) ;
117
+ if ( isCommenting ) return ;
118
+ commentPost ( ) ;
89
119
} ;
90
120
91
121
const handleLikePost = ( ) => {
0 commit comments