Skip to content

Commit

Permalink
Merge pull request #189 from prgrms-web-devcourse-final-project/feat/#…
Browse files Browse the repository at this point in the history
…174

로그인 정보 로컬스토리지 저장 및 이에 따른 프로필 하위페이지 수정
  • Loading branch information
Builter251 authored Dec 8, 2024
2 parents c708c65 + 62caa3a commit c065d62
Show file tree
Hide file tree
Showing 16 changed files with 177 additions and 124 deletions.
8 changes: 2 additions & 6 deletions src/apis/reviewService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,9 @@ import { data } from './../pages/TimelinePage/mockData'
import fetchApi from './ky'

const reviewService = {
postMateReview: async (
memberid: number,
postId: number,
jsonData: unknown,
) => {
postMateReview: async (postId: number, jsonData: unknown) => {
const response = await fetchApi
.post(`mates/${memberid + 1}/${postId}/reviews`, {
.post(`mates/${postId}/reviews`, {
headers: {
'Content-Type': 'application/json',
},
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useEditMyInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import { useMutation } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'

const useEditMyInfo = () => {
const useEditMyInfo = (memberId: number) => {
const { mutate, isPending, isError, error, isSuccess } = useMutation({
mutationFn: (formData: FormData) => userService.editMyInfo(formData),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY.MY_INFO, 1] })
queryClient.invalidateQueries({ queryKey: [QUERY_KEY.MY_INFO, memberId] })
toast('정보 수정이 완료되었습니다.')
},
onSettled: (data, error) => {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useGetMyInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { QUERY_KEY } from '@apis/queryClient'
import userService from '@apis/userService'
import { useQuery } from '@tanstack/react-query'

const useGetMyInfo = (userId) => {
const useGetMyInfo = (userId: number) => {
const { data, isPending, isError, error } = useQuery({
queryKey: [QUERY_KEY.MY_INFO, userId],
queryFn: async () => userService.getMyInfo(userId),
Expand Down
13 changes: 3 additions & 10 deletions src/hooks/useReviewHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,11 @@ import { useMutation, useQuery } from '@tanstack/react-query'

export const useMutateMateReview = () =>
useMutation({
mutationFn: (data: {
memberId: number
matePostId: number
jsonData: unknown
}) =>
reviewService.postMateReview(
data.memberId,
data.matePostId,
data.jsonData,
),
mutationFn: (data: { matePostId: number; jsonData: unknown }) =>
reviewService.postMateReview(data.matePostId, data.jsonData),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEY.MATE_REVIEW] })
queryClient.invalidateQueries({ queryKey: [QUERY_KEY.TIMELINE_LIST] })
},
})

Expand Down
2 changes: 1 addition & 1 deletion src/layouts/GlobalNav/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { useUserStore } from '@store/useUserStore'
const GlobalNav = () => {
const { pathname } = useLocation()
const [isLogin, setIsLogin] = useState<boolean>(false)
const { memberId } = useUserStore().userInfo
const memberId = localStorage.getItem('memberId')

useEffect(() => {
const token = localStorage.getItem('token')
Expand Down
5 changes: 3 additions & 2 deletions src/pages/GoodsDetailPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@ import KakaoMapContainer from './KakaoMapContainer'
import GoodsHostButton from './GoodsHostButton'
import GoodsVisitorButton from './GoodsVisitorButton'
import { useCreateGoodsChatroom } from '@hooks/useCreateChatRoom'
import { useUserStore } from '@store/useUserStore'

const GoodsDetailPage = () => {
const [localUserId, setLocalUserId] = useState(localStorage.getItem('userId'))
const { memberId } = useUserStore().userInfo

const { id: goodsId } = useParams()

Expand Down Expand Up @@ -206,7 +207,7 @@ const GoodsDetailPage = () => {
: `${formatPriceWithComma(price)}원`}
</GoodsPriceText>
<GoodsBottomButtonWrap>
{Number(localUserId) === seller.memberId ? (
{Number(memberId) === seller.memberId ? (
<GoodsHostButton
onClickDeleteButton={onClickDeleteButton}
onClickEditButton={onClickEditButton}
Expand Down
14 changes: 11 additions & 3 deletions src/pages/GoodsRecordPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import SubHeader from '@layouts/SubHeader'
import GoodsRecordBox from './GoodsRecordBox'
import { GoodsSection, NoGoodsList } from './style'

import { useEffect, useState } from 'react'
import { useLocation, useParams } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import { useInfiniteQuery } from '@tanstack/react-query'
import { QUERY_KEY } from '@apis/queryClient'
import userService from '@apis/userService'
import { useInView } from 'react-intersection-observer'
import { RefContainer } from '@styles/globalStyle'
import Spinner from '@components/Spinner'
import { toast } from 'react-toastify'
import { ROUTE_PATH } from '@constants/ROUTE_PATH'

const HEADER_TEXT = {
sold: '굿즈 판매기록',
Expand All @@ -27,8 +29,9 @@ interface GoodsRecord {

const GoodsRecordPage = () => {
const location = useLocation()
const navigate = useNavigate()
const { id } = useParams()
const [memberId, setMemberId] = useState(1)
const currentUserId = localStorage.getItem('memberId')
const [pageType, setPageType] = useState<('sold' | 'bought') | null>(
location.state.type,
)
Expand All @@ -52,6 +55,11 @@ const GoodsRecordPage = () => {

useEffect(() => {
window.scrollTo(0, 0)
if (pageType === 'bought') {
currentUserId !== id &&
(toast('굿즈 구매기록은 본인만 볼수있습니다.'),
navigate(ROUTE_PATH.HOME))
}
}, [])

useEffect(() => {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/GoodsRecordPage/style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,5 @@ export const NoGoodsList = styled.div`
align-items: center;
font-size: ${theme.fontSize.xlarge};
font-weight: ${theme.fontWeight.semi};
font-size: ${theme.fontColor.black};
color: ${theme.fontColor.black};
`
18 changes: 12 additions & 6 deletions src/pages/ProfilePage/ProfileEdit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ProfileImageEdit,
ProfileImageEditWrap,
ProfileSpinnerWrap,
ValidateText,
} from './style'
import { FormEvent, useEffect, useState } from 'react'
import { handleImageUpload } from './methods'
Expand All @@ -20,6 +21,7 @@ import { kboTeamInfo } from '@constants/kboInfo'
import { ROUTE_PATH } from '@constants/ROUTE_PATH'
import Spinner from '@components/Spinner'
import { useUserStore } from '@store/useUserStore'
import { toast } from 'react-toastify'

// 소개글 글자제한
const MAX_LENGTH = 500
Expand All @@ -38,7 +40,9 @@ const ProfileEdit = () => {
undefined,
)

const { mutateMyInfo, error, isError, isPending, isSuccess } = useEditMyInfo()
const { mutateMyInfo, error, isError, isPending, isSuccess } = useEditMyInfo(
Number(memberId),
)

// 프로파일 수정 사항 서브밋
const onProfileEditSubmit = (e: FormEvent<HTMLFormElement>) => {
Expand All @@ -49,20 +53,22 @@ const ProfileEdit = () => {
nickname: userInfo?.nickname,
aboutMe: userInfo?.aboutMe,
// 멤버아이디 수정요청
memberId: 1,
memberId: memberId,
}
const formData = new FormData()

formData.append(
'data',
new Blob([JSON.stringify(dataObject)], { type: 'application/json' }),
)
profileImg && formData.append('image', profileImg)
profileImg && formData.append('file', profileImg)

try {
mutateMyInfo(formData)
navigate(`${ROUTE_PATH.PROFILE}/${memberId}`)
} catch (err) {}
} catch (err) {
toast('이런! 오류가 발생했어요.')
}
}

// 소개글 글자제한
Expand Down Expand Up @@ -173,9 +179,9 @@ const ProfileEdit = () => {
handleChange(e)
}}
></textarea>
<p>
<ValidateText>
{userInfo?.aboutMe ? userInfo?.aboutMe.length : '0'}/{MAX_LENGTH}
</p>
</ValidateText>
</ProfileEditInputWrap>

<ProfileEditInputWrap>
Expand Down
31 changes: 18 additions & 13 deletions src/pages/ProfilePage/ProfileMain.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,24 @@ import Skeleton from 'react-loading-skeleton'
import 'react-loading-skeleton/dist/skeleton.css'
import useGetMyInfo from '@hooks/useGetMyInfo'
import { UserInfo } from '@typings/userForm'
import { toast } from 'react-toastify'
import { useUserStore } from '@store/useUserStore'

import Alert from '@components/Alert'
import ALERT_MESSAGE from '@constants/alertMessage'
import { logoutPost } from '@apis/logoutService'
import { formatManner } from '@utils/formatManner'

const ProfileMain = () => {
const alertRef = useRef<HTMLDialogElement | null>(null)
const navigate = useNavigate()
const { id } = useParams()

const { memberId: loginMemberId } = useUserStore().userInfo
const loginMemberId = localStorage.getItem('memberId')

const [userId, setUserId] = useState(id)
const [isMyProfile, setIsMyProfile] = useState<boolean | null>(null)
const [userInfo, setUserInfo] = useState<UserInfo | null>(null)

const myInfoResult = useGetMyInfo(loginMemberId)
const myInfoResult = useGetMyInfo(Number(loginMemberId))
const userInfoResult = useGetUserInfo(
typeof id === 'string' ? Number(id) : null,
)
Expand All @@ -71,13 +70,14 @@ const ProfileMain = () => {
}

useEffect(() => {
if (loginMemberId === Number(userId)) {
if (Number(loginMemberId) === Number(userId)) {
setIsMyProfile(true)
} else {
setIsMyProfile(false)
}
}, [userId])

// 자기 프로필 판단해서 데이터 로드함
useEffect(() => {
if (isMyProfile !== null) {
if (isMyProfile) {
Expand All @@ -88,6 +88,7 @@ const ProfileMain = () => {
}
}, [isMyProfile, myInfoResult.getMyInfo, userInfoResult.getUserInfo])

// 프로필 수정 페이지 이동함수
const onNavigateEdit = () => {
navigate('/profile/edit', { state: { ...userInfo } })
}
Expand Down Expand Up @@ -128,7 +129,7 @@ const ProfileMain = () => {
style={{ display: 'none' }}
/>
</ProfileEditWrap>
<ProfileFollowWrap>
{/* <ProfileFollowWrap>
<Link to={ROUTE_PATH.FOLLOW}>
<div>
<p>팔로우</p>
Expand All @@ -139,12 +140,18 @@ const ProfileMain = () => {
<p>{userInfo?.followerCount}</p>
</div>
</Link>
</ProfileFollowWrap>
</ProfileFollowWrap> */}
</ProfileTopWrap>

{/* 프로필 소개 섹션 */}
<ProfileNotice>
<p>{userInfo?.aboutMe}</p>
<p
dangerouslySetInnerHTML={{
__html: userInfo?.aboutMe
? userInfo?.aboutMe.replace(/\n/g, '<br>')
: '',
}}
></p>
</ProfileNotice>

{/* 프로필 상단 버튼 본인 프로필 유무 */}
Expand Down Expand Up @@ -176,15 +183,13 @@ const ProfileMain = () => {
<ProfileMannerInfo>
<span>첫 타율 0.300</span>
<p>
{(userInfo && userInfo.manner) || (
<Skeleton containerClassName='skeleton-flex' />
)}
{userInfo && formatManner(userInfo.manner)}
<MannerIcon />
</p>
<ProfileMannerGraph>
{(userInfo && (
{userInfo && (
<ProfileMannerGraphInner width={userInfo.manner * 100} />
)) || <Skeleton />}
)}
</ProfileMannerGraph>
</ProfileMannerInfo>
</ProfilePadding>
Expand Down
9 changes: 8 additions & 1 deletion src/pages/ProfilePage/ReviewBoxComponent/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ const ReviewBoxComponent = ({
reviewList: ReviewContent[]
selectedReview: string
}) => {
const decideLink = (reviewType: string, postId: number) => {
if (reviewType && reviewType === '2') {
return `/mate-detail/${postId}`
} else if (reviewType && reviewType === '1') {
return `/goods-detail/${postId}`
}
}
return (
<ReviewWrap>
{reviewList && reviewList.length !== 0 ? (
Expand All @@ -31,7 +38,7 @@ const ReviewBoxComponent = ({
{data.nickname} · {formatReviewPageTime(data.createdAt)}
</em>
<ReviewLinkBox>
<Link to={'/'}>
<Link to={decideLink(selectedReview, data.postId)}>
<div>
<span>
{selectedReview === '2' && '직관후기'}
Expand Down
11 changes: 11 additions & 0 deletions src/pages/ProfilePage/ReviewPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ const MATE_REVIEW = '2'

const ReviewPage = () => {
const { id: pageId } = useParams()
const memberId = localStorage.getItem('memberId')

const [isMy, setIsMy] = useState(false)
const [selectedReview, setSelectedReview] = useState(GOODS_REVIEW)
const { ref, inView } = useInView({
threshold: 0.5,
Expand All @@ -31,6 +34,14 @@ const ReviewPage = () => {
}
}

useEffect(() => {
if (pageId === memberId) {
setIsMy(true)
} else {
setIsMy(false)
}
}, [memberId])

const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
useInfiniteQuery({
queryKey: [QUERY_KEY.REVIEW_LIST, selectedReview],
Expand Down
13 changes: 6 additions & 7 deletions src/pages/ProfilePage/style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,14 +259,13 @@ export const ProfileEditInputWrap = styled.div`
border-radius: 4px;
cursor: pointer;
}
`

& > p {
font-size: ${theme.fontSize.small};
color: ${theme.fontColor.black};
position: absolute;
bottom: calc(1em + 8px);
right: 28px;
}
export const ValidateText = styled.p`
font-size: ${theme.fontSize.small};
color: ${theme.fontColor.black};
text-align: right;
margin-top: 0.25em;
`

// 후기 모아보기 페이지
Expand Down
4 changes: 3 additions & 1 deletion src/pages/ReviewWritePage/ReviewPostInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,17 @@ const ReviewPostInfo = ({
reviewType,
title,
nickname,
postImageUrl,
}: {
reviewType: string
title: string
nickname: string | undefined
postImageUrl: string
}) => {
return (
<ReviewPostWrap>
<ReviewPostImage>
<img src='https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcS4tKSd2NValZoc5cMRlfECFB2KA2qwqLAp5oN9UEHid-yEOv-IXdGsrpqGaxqdvTjtV42R5dLOiLXiGhkdq2qHTQ' />
<img src={postImageUrl} />
</ReviewPostImage>
<ReviewPostInfoWrap>
<ReviewPostTitle>{title}</ReviewPostTitle>
Expand Down
Loading

0 comments on commit c065d62

Please sign in to comment.