Built Twitter Like App - 24

Add Post Page

  1. Add Post API
  2. Add Hooks
  3. Add Post Page

Add Post API

Add file pages/posts/[postId].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
import { NextApiRequest, NextApiResponse } from "next";
import prisma from '@/libs/prismadb';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'GET') {
return res.status(405).end();
}

try{
const { postId } = req.query;

if (isNaN(Number(postId))) {
throw new Error('Invalid Post ID');
};

//console.log('prisma postId',postId,typeof postId );

const post = await prisma.post.findUnique({
where: {
id: Number(postId)
},
include: {
user: true,
comments: {
include: {
user: true
},
orderBy: {
createdAt: 'desc'
}
}
}
});

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

Add Hook

Add file hooks/usePost.ts :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import useSWR from 'swr';

import fetcher from '../libs/fetcher';

const usePost = ( postId:string) => {
const url = postId ? `/api/posts/${postId}` : null
const {
data,
error,
isLoading,
mutate
} = useSWR(url, fetcher)
return {
data,
error,
isLoading,
mutate
}
};

export default usePost;

Add Post Page

Add file pages/posts/[postId].tsx :

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
import { useRouter } from "next/router";
import { ClipLoader } from "react-spinners";

import Header from "@/components/Header";
import usePost from "@/hooks/usePost";
import PostItem from "@/components/posts/PostItem";
import Form from "@/components/Form";

const PostView = () => {
const router = useRouter();
const { postId } = router.query;

const { data: fetchedPost, isLoading } = usePost(postId as string);

if (isLoading || !fetchedPost) {
return (
<div className="
flex
justify-center
items-center
h-full
">
<ClipLoader color="lightblue" size={90} />
</div>
)
}

return (
<>
<Header label={"Tweet"} showBackArrow />
<PostItem data={fetchedPost} userId={fetchedPost.user.id} />
<Form
postId={postId as string}
isComment
placeholder="Tweet your reply"
/>
</>
)
}

export default PostView;

Demo:

请我喝杯咖啡吧~

支付宝
微信