Built Twitter Like App - 23

Add Follow Function

  1. Add Follow API
  2. Add hook
  3. Modify component UserBio

Add Follow API

Add file /page/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/useFollow.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
import { useCallback, useMemo } from "react";
import useCurrentUser from "./useCurrentUser";
import useLoginModal from "./useLoginModal";
import useUser from "./useUser";
import toast from "react-hot-toast";
import axios from "axios";
import useFollowlist from "./useFollowlist";

const useFollow = (userId : number) => {
const { data: currentUser, mutate: mutateCurrentUser } = useCurrentUser();
const { mutate: mutateFetchedUser } = useUser( userId );
const { data: followlist,mutate: mutateFetchedFollowerlist } = useFollowlist( currentUser?.id );

const loginModel = useLoginModal();

const isFollowing = useMemo(() => {
const list = followlist?.map( (item: { followingId: any; }) => item.followingId) || [];

//console.log('followlistLength',list, followlist,userId);
return list.includes(userId);
},[ followlist,userId ]);

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

try{
let request;

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

await request();

mutateCurrentUser();
mutateFetchedUser();
mutateFetchedFollowerlist();

toast.success('Success');

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

},[loginModel,currentUser,userId,isFollowing,mutateCurrentUser,mutateFetchedUser]);

return {
isFollowing,
toggleFollow
}
}

export default useFollow;

Modify UseBio

modify file components/users/UserBio.tsx:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
...
const { isFollowing, toggleFollow } = useFollow( Number(userId) );
...
<div className='border-b-[1px] border-neutral-800 pb-4'>
<div className='flex justify-end p-2'>
{currentUser?.id === Number(userId) ? (
<Button secondary label='Edit' onClick={ editModal.onOpen } />
) : (
<Button
onClick={toggleFollow}
label={ isFollowing ? 'Unfollow' : 'Follow' }
secondary={!isFollowing}
outline={isFollowing}
/>
)}
</div>
...

Demo

Initial:

Click Follow Button:

请我喝杯咖啡吧~

支付宝
微信