Skip to content

Commit

Permalink
Merge pull request #321 from prgrms-fe-devcourse/bug-post-update
Browse files Browse the repository at this point in the history
🐛 게시글 수정 후 좋아요 싫어요 동작 안하는 문제 수정
  • Loading branch information
khj0426 authored Oct 2, 2023
2 parents 8dce411 + dd2e501 commit 898c51e
Show file tree
Hide file tree
Showing 13 changed files with 71 additions and 54 deletions.
3 changes: 2 additions & 1 deletion src/app/(root)/(routes)/post/[postId]/modify/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import Post from '@/types/post'

async function getPostData(postId: string): Promise<Post> {
const res = await getPostDetail(postId)
const { post } = res
const { post, disLikePost } = res
const { title, description } = await JSON.parse(post.title)
post.title = title
post.description = description
post.mapping_ID = disLikePost._id
return post
}

Expand Down
8 changes: 1 addition & 7 deletions src/app/api/post/[postId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,7 @@ async function fetchPostDetail(id: string) {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_ADDRESS}/posts/${id}`,
{
cache: 'no-cache',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
cache: 'no-store',
},
)

Expand Down Expand Up @@ -44,7 +39,6 @@ export async function GET(req: NextRequest) {
const dislikePostDetail: Post = await fetchPostDetail(
foreign_postDetail_key,
)

return new Response(
JSON.stringify({ post: postDetail, disLikePost: dislikePostDetail }),
{ status: 200 },
Expand Down
8 changes: 2 additions & 6 deletions src/app/api/posts/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NextRequest } from 'next/server'
import { Environment } from '@/config/environments'
import Post from '@/types/post'

async function getAllPosts(id: string, offset: string, limit: string) {
async function getAllPosts(id: string, offset?: string, limit?: string) {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_ADDRESS}/posts/channel/${id}?offset=${offset}&limit=${limit}`,
Expand Down Expand Up @@ -31,11 +31,7 @@ export async function GET(req: NextRequest) {
const limit = searchParams.get('limit') as string
try {
const posts = await getAllPosts(id || '', offset, limit)
const disLikesPosts = await getAllPosts(
disLikeChannelId || '',
offset,
limit,
)
const disLikesPosts = await getAllPosts(disLikeChannelId || '')

const parsedPosts = posts.map((post: Post) => {
const parsedArticle = JSON.parse(post.title)
Expand Down
34 changes: 29 additions & 5 deletions src/app/api/posts/update/route.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,46 @@
import { NextResponse } from 'next/server'
import { Environment } from '@/config/environments'
import { POST_CONSTANT } from '@/constants/post'
import { useServerCookie } from '@/hooks/useServerCookie'
import { apiServer } from '@/lib/axiosSever'
import type Post from '@/types/post'

export async function PUT(request: Request) {
const formData = await request.formData()
const channelId = Environment.channelId()
formData.append('channelId', channelId)
const { CHANNEL_ID } = POST_CONSTANT

const { token } = useServerCookie()
try {
const { data } = await apiServer.put(`/posts/update`, formData, {

const updatePost = async (
formData: FormData,
channelId: string,
mapping_ID: string,
): Promise<Post> => {
formData.delete(CHANNEL_ID)
formData.append(CHANNEL_ID, channelId)
if (mapping_ID) {
const getTitleField = JSON.parse(formData.get('title') as string)
getTitleField.mapping_ID = mapping_ID
formData.set('title', JSON.stringify(getTitleField))
}
const { data } = await apiServer.put('/posts/update', formData, {
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'multipart/form-data',
},
})
return NextResponse.json(data)

return data
}

try {
const formData = await request.formData()
const mapping_ID = JSON.parse(
formData.get('title')?.toString() || '',
).mapping_ID

const updatePostRes = await updatePost(formData, channelId, mapping_ID)
return NextResponse.json(updatePostRes)
} catch (error: any) {
return NextResponse.json(
{ error: error.response.data.message },
Expand Down
16 changes: 13 additions & 3 deletions src/app/api/users/route.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import { NextResponse } from 'next/server'
import { apiServer } from '@/lib/axiosSever'
import { Environment } from '@/config/environments'

export async function GET(_request: Request) {
try {
const { data } = await apiServer.get(`/users/get-users`)
const allUserRes = await fetch(`${Environment.baseUrl()}/users/get-users`, {
next: {
revalidate: 5,
},
})

return new Response(JSON.stringify(data))
if (allUserRes.ok) {
const allUser = await allUserRes.json()

return new Response(JSON.stringify(allUser))
}

return new Response(JSON.stringify(allUserRes))
} catch (error: any) {
return NextResponse.json(
{ error: error.response.data.message },
Expand Down
3 changes: 2 additions & 1 deletion src/components/molcules/EditNamesForm/EditNamesform.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ const EditNamesform = ({ fullName }: NameProps) => {
setCurrentName(data.fullName)
notify('success', '닉네임이 수정되었습니다.')
setValue('fullName', '')
location.reload()
} catch (error) {
notify('error', '닉네임 수정에 실패했습니다.')
} finally {
location.reload()
}
})}
style={{ display: 'flex', justifyContent: 'space-between' }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,7 @@ export default function LikeDislikeContainer({
<>
<span className="like-container__likes">
<Image
src={
likeState === 'like' || likeState === 'both'
? Assets.ActiveLike
: likeImage
}
src={likeState === 'like' ? Assets.ActiveLike : likeImage}
alt="좋아요 이미지"
width={30}
height={30}
Expand All @@ -88,11 +84,7 @@ export default function LikeDislikeContainer({
/>
<span className="like-container__dislikes">
<Image
src={
likeState === 'dislike' || likeState === 'both'
? Assets.ActiveDisLike
: disLikeImage
}
src={likeState === 'dislike' ? Assets.ActiveDisLike : disLikeImage}
alt="싫어요 이미지"
width={30}
height={30}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import UserList from './UserList'

export default async function HydratedUserList() {
const queryClient = getQueryClient()
await queryClient.prefetchQuery(['getAllUsers'], getAllUsers)
await queryClient.prefetchQuery(['getAllUsers'], getAllUsers, {
staleTime: Infinity,
})
const dehydratedState = dehydrate(queryClient)

return (
Expand Down
7 changes: 5 additions & 2 deletions src/components/organisms/NavBar/UserList/UserList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ import Avatar from '@/components/atoms/Avatar'
import { Text } from '@/components/atoms/Text'
import APP_PATH from '@/config/paths'
import useFollow from '@/hooks/useFollow'
import useGetAllUsers from '@/queries/users'
import { useGetAllUsers } from '@/queries/users'
import { UserSummary } from '@/types/user'

export default function UserList() {
const { data } = useGetAllUsers()

return (
<>
<div className="nav-title">
Expand All @@ -21,7 +22,9 @@ export default function UserList() {
</div>
</div>
<ul className="avatar-list">
{data?.map((user) => <UserListItem key={user._id} userData={user} />)}
{data?.map((user: UserSummary) => (
<UserListItem key={user._id} userData={user} />
))}
</ul>
</>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export default function ModifyPostPageTemplate({
image: postData.image,
imageToDeletePublicId: postData.imagePublicId,
})
setValue('mapping_ID', postData.mapping_ID ?? '')
}, [postData, setValue])

useEffect(() => {
Expand Down
7 changes: 6 additions & 1 deletion src/hooks/useModifyPostForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export const modifyUploadFormSchema = z.preprocess(
image: z.any(),
imageToDeletePublicId: z.string().optional(),
}),
mapping_ID: z.string(),
}),
)

Expand All @@ -51,6 +52,7 @@ export const useModifyPostForm = () => {
description,
postId,
imageSelective,
mapping_ID,
}: ModifyUploadFormType) => {
if (isSubmitting) return
setIsSubmitting(() => true)
Expand All @@ -60,15 +62,18 @@ export const useModifyPostForm = () => {
description,
postId,
imageSelective,
mapping_ID,
})
if (res) {
router.push(APP_PATH.postDetail(postId))
notify('success', '게시글이 성공적으로 등록되었습니다.')
setIsSubmitting(() => false)
}
} catch (e) {
notify('error', '게시글 등록에 실패했습니다.')
setIsSubmitting(() => false)
} finally {
router.push(APP_PATH.postDetail(postId))
router.refresh()
}
}

Expand Down
20 changes: 3 additions & 17 deletions src/queries/users/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,9 @@
import { useQuery } from '@tanstack/react-query'
import { useCurrentUser } from '@/hooks/useCurrentUser'
import { getAllUsers } from '@/services/user'
import { UserSummary } from '@/types/user'

const useGetAllUsers = () => {
const { currentUser } = useCurrentUser()
export const useGetAllUsers = () => {
return useQuery({
queryKey: [
'getAllUsers',
currentUser?._id,
currentUser?.coverImage,
currentUser?.fullName,
currentUser?.name,
],
queryFn: async () => {
const data: UserSummary[] = await getAllUsers()
return data
},
queryKey: ['getAllUsers'],
queryFn: getAllUsers,
})
}

export default useGetAllUsers
2 changes: 2 additions & 0 deletions src/services/post/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ export const putUserPost = async (body: ModifyUploadFormType) => {
const title = JSON.stringify({
title: body.title,
description: body.description,
mapping_ID: body.mapping_ID,
})

const formData = new FormData()
formData.append('title', title)
formData.append('postId', body.postId)
Expand Down

0 comments on commit 898c51e

Please sign in to comment.