Skip to content

Commit

Permalink
Merge pull request #197 from bsideproject/feature/user
Browse files Browse the repository at this point in the history
[feat] Liked 페이지 우선 커밋.......!!
  • Loading branch information
KinDDoGGang authored Oct 22, 2023
2 parents aa07ddd + b521ca5 commit d7c688e
Show file tree
Hide file tree
Showing 6 changed files with 170 additions and 11 deletions.
19 changes: 18 additions & 1 deletion api/userInfo.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { UserInfoProps } from '../context/UserInfoProvider.tsx';
import { UserInfoProps } from '@/context/UserInfoProvider.tsx';
import { RoomSearch } from '@/public/types/room';
import { fetchData } from '.';

export const getProfile = async () => {
Expand All @@ -9,3 +10,19 @@ export const getProfile = async () => {
},
});
};

export const getLikedRooms = async (page: number) => {
let result;
try {
result = await fetchData<ReturnData<RoomSearch[]>>(`/api/v1/my/rooms/like/${page}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
} catch (error) {
console.error('userInfo Error', error);
throw Error('no Liked Rooms', error as Error);
}
return result;
};
4 changes: 0 additions & 4 deletions components/Nav/Nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,6 @@ export default function Nav({ initMenu, profile }: NavProps) {
);
};

useEffect(() => {
console.log('userInfoData in Nav', profile);
}, [profile]);

return (
<div className={`${styles.container} grid grid-cols-${menus.length} bg-g0 w-full h-[66px] text-center`}>
{menus.map((menu, index) => {
Expand Down
1 change: 0 additions & 1 deletion pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ function Home() {
try {
const data = await getProfile();
if (data != null) {
console.log('data info userProfile', data);
setProfile(data);
}
} catch (error) {
Expand Down
155 changes: 151 additions & 4 deletions pages/liked/index.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,82 @@
/* eslint-disable react/no-unstable-nested-components */
import React from 'react';
import React, { useRef, useEffect, useState } from 'react';
import NoLiked from '@/public/icons/noLiked.svg';
import useModal from '@/hooks/useModal';
import DefaultLayout from '@/components/layouts/DefaultLayout';
import { Nav, Typography } from '@/components/index.tsx';
import { Nav, Typography, Chip } from '@/components/index.tsx';
import { useRouter } from 'next/router';
import { RoomSearch } from '@/public/types/room';
import { getLikedRooms } from '@/api/userInfo';
import FilterImg from '@/public/icons/filter.svg';
import Filter from '@/components/Filter/Filter.tsx';
import isEmpty from 'lodash-es/isEmpty';
// TODO 데이터가 구체화되면 바꿔줘야함
interface MyPostingProps {
roomInfo: any | null;
}
const FILTER_LABEL: Record<string, string> = {
locationIds: 'Location',
maxDeposit: 'Deposit',
maxMonthlyRent: 'Monthly rent',
availableDate: 'Date available',
types: 'Type of housing',
furnishingTypes: 'Furnishing',
};

export default function Liked({ roomInfo }: MyPostingProps) {
const router = useRouter();
const { openModal, closeModal } = useModal();
const [page, setPage] = useState(0);
const [filters, setFilters] = useState<string[]>([]);
const [rooms, setRooms] = useState<RoomSearch[]>([]);
const [searchParams, setSearchParams] = useState<Record<string, string>>({});
const [totalElements, setTotalElements] = useState(0);
const target = useRef(null);
const options = {
threshold: 1.0,
};
const callback = async (entries: IntersectionObserverEntry[]) => {
const [{ isIntersecting }] = entries;
if (isIntersecting) {
setPage((prev) => prev + 1);
}
};

// useEffect(() => {
// (async () => {
// try {
// const data = await getLikedRooms(page);
// if (data?.error) {
// setRooms([]);
// } else {
// setRooms((prevRooms) => [...prevRooms, ...(data?.content || [])]);
// setTotalElements(data?.totalElements || 0);
// }
// } catch (error) {
// setRooms([]);
// }
// })();
// }, [page]);

useEffect(() => {
(async () => {
try {
const result = await getLikedRooms(page);
if (result?.error) {
// 비동기 함수 내부에서 에러를 처리하고 적절한 값을 반환하도록 구현되었을 때
setRooms([]);
}
if (target?.current) {
const observer = new IntersectionObserver(callback, options);
observer.observe(target.current);
}
} catch (error) {
setRooms([]);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [router.query]);

/**
* 좋아요 없을 때 보여주는 Component
*/
Expand Down Expand Up @@ -47,10 +112,91 @@ export default function Liked({ roomInfo }: MyPostingProps) {
};

const LikedComponent = () => {
// 옵션 제거 시 실행될 함수
const [clickedChip, setClickedChip] = useState('');
const makeFilters = (filterParams: Record<string, string>) => {
const resultFilter: string[] = [];
Object.keys(filterParams).forEach((key) => {
if (!isEmpty(filterParams[key])) {
resultFilter.push(FILTER_LABEL[key]);
}
});
setFilters(() => [...resultFilter]);
};
const getChildData = async (childData: Record<string, string>) => {
makeFilters(childData);
setPage(0);
setSearchParams(childData);
setRooms([]);
};
const openFilterPopup = () => {
openModal({
props: {
title: 'Filters',
size: 'full',
custom: true,
customHeader: false,
},
children: <Filter closeModal={closeModal} getChildData={getChildData} />,
});
};
const handleChipClick = (label: React.SetStateAction<string>) => {
setClickedChip(label);
};
const handleOptionRemove = (option: string, index: number) => {
const resultFilters = filters.filter((item) => item !== option);
setFilters(() => [...resultFilters]);

const selectedOption = Object.keys(FILTER_LABEL).find((key) => {
return FILTER_LABEL[key] === option;
});
setPage(0);
setRooms([]);
setSearchParams((prev) => {
return {
...prev,
[selectedOption as string]: '',
};
});

// 선택된 칩이 없거나 클릭된 칩이 삭제된 칩인 경우에 맨 처음 칩을 clickedChip으로 설정
if ((clickedChip || '') === '') {
setClickedChip(filters?.[0]);
}
};
const handlePropsClick = (option: string, index: number) => {
let result = false;
if ((clickedChip || '') !== '' && filters.length > 1) {
result = filters[0] === option;
} else if (filters.length === 1) {
result = option === filters[0];
}
return result;
};
return (
<div>
<div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap' }} className="mb-[8px]">
<FilterImg
className="stroke-g7 stroke-[2] cursor-pointer "
onClick={openFilterPopup}
style={{ alignSelf: 'flex-start' }}
/>
{filters.map((label, index) => {
return (
<div style={{ marginLeft: index === 0 ? '4px' : '0', marginRight: '-4px' }} key={index}>
<Chip
key={`${label}-${index}`}
label={label}
onDelete={() => handleOptionRemove?.(label, index)}
onChipClick={() => handleChipClick?.(label)}
clicked={handlePropsClick?.(label, index)}
/>
</div>
);
})}
</div>
<Typography variant="body" customClassName="text-left font-bold text-[16px] text-g7">
There are <span className="text-r1">{`${(roomInfo || []).length} rooms`}</span> in total!
There are <span className="text-r1">{`${totalElements} rooms`}</span> in total!
</Typography>
{/* {rooms.map((room, idx) => (
<div className={`mt-[20px] ${rooms.length - 1 === idx ? 'mb-[83px]' : ''}`} key={`room-${idx}`}>
Expand All @@ -65,14 +211,15 @@ export default function Liked({ roomInfo }: MyPostingProps) {
</div>
</div>
</div>
<div ref={target} />
</div>
);
};

/**
* 좋아요 있을 때 보여주는 Component (TODO : 구체화 해줘야함)
*/
return (roomInfo || []).length === 0 ? <NoPostings /> : <LikedComponent />;
return (rooms || []).length === 0 ? <NoPostings /> : <LikedComponent />;
}

Liked.getLayout = function getLayout(page: React.ReactElement) {
Expand Down
1 change: 0 additions & 1 deletion pages/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ export default function Login() {
try {
const data = await getProfile();
if (data != null) {
console.log('data info userProfile', data);
setUserInfoData(data);
}
} catch (error) {
Expand Down
1 change: 1 addition & 0 deletions public/types/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ interface ReturnData<T> {
sort: Sort;
totalElements: number;
totalPages: number;
error?: string;
}

0 comments on commit d7c688e

Please sign in to comment.