Built Twitter Like App - 25

Add Like Function

  1. Add Like API
  2. Add Hooks
  3. Modify PostItem Page

Add Like API

Add file pages/api/follow.ts :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { NextApiRequest, NextApiResponse } from "next";

import primsa from '@/libs/prismadb';

export default async function handler(
req : NextApiRequest,
res : NextApiResponse
) {
if( req.method !== 'POST' && req.method !== 'DELETE' ) {
return res.status(405).end();
}

try{
const { userId } = req.body;
const { currUser } = req.query;
const currentUserId = Number(currUser);

//console.log('currentuser user', currentUserId, userId);

if(!userId) {
throw new Error('Invalid ID');
}

if(!currentUserId) {
throw new Error('Invalid currentUserId');
}

if(req.method === 'POST') {
await primsa.followingId.create({
data: {
userId: currentUserId,
followingId: userId
}
});
}

if(req.method === 'DELETE') {
await primsa.followingId.deleteMany({
where: {
userId: currentUserId,
followingId: userId
}
});
}

return res.status(200).end();
} catch(error){
console.log(error);
return res.status(400).end();
}
}

Add Hook

Add file hooks/useLike.ts :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

import { useCallback, useMemo } from "react";
import useCurrentUser from "./useCurrentUser";
import useLoginModal from "./useLoginModal";
import toast from "react-hot-toast";
import axios from "axios";
import usePost from "./usePost";
import useLikelist from "./useLikelist";
import usePosts from "./usePosts";

const useLike = ( postId : number ,userId : number) => {
const { data: currentUser } = useCurrentUser();

const { data: fetechedPost, mutate: mutateFetchedPost } = usePost( postId );
const { data: likelist,mutate: mutateFetchedLikelist } = useLikelist( postId );
const { mutate: mutateFetchedPosts } = usePosts(userId);

const loginModel = useLoginModal();

const hasLikes = useMemo(() => {
const list = likelist?.map( (item: { likedId: any; }) => item.likedId) || [];

//console.log('haslikes', list.includes(currentUser?.id), postId , currentUser?.id );
return list.includes(currentUser?.id);
},[ likelist ]);

const toggleLike = useCallback(async () => {
if(!currentUser){
return loginModel.onOpen();
}

try{
let request;

if (hasLikes) {
request = () => axios.delete(`/api/like?currUser=${currentUser.id}`, { data: { postId }});
} else{
request = () => axios.post(`/api/like?currUser=${currentUser.id}`, { postId });
}

await request();

mutateFetchedPost();
mutateFetchedLikelist();
mutateFetchedPosts();

toast.success('Success');

} catch(error){
toast.error('Something went wrong useLike');
}

},[
loginModel,
currentUser,
postId,
hasLikes,
mutateFetchedPost,
mutateFetchedLikelist,
mutateFetchedPosts
]);

return {
hasLikes,
toggleLike
}
}

export default useLike;

Modify PostItem:

Modify file components/posts/PostItem.tsx :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
...
import useLike from "@/hooks/useLike";
...
const userId_Num = Number(userId);
const { hasLikes, toggleLike } = useLike( data.id, userId_Num );
...
const onLike = useCallback((event: any) => {
event.stopPropagation();

if (!currentUser) {
return loginModel.onOpen();
}

toggleLike();
},[loginModel, currentUser, toggleLike])
...
const LikeIcon = hasLikes ? AiFillHeart : AiOutlineHeart;
...
<LikeIcon size={20} color={hasLikes? "red" : ""} />
<p>
{likelist?.length || 0}
</p>
...

Demo

请我喝杯咖啡吧~

支付宝
微信