Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

즐겨찾기 on/off에 따른 DB의 post star 카운팅 #184

Merged
merged 10 commits into from
Mar 30, 2022
14 changes: 11 additions & 3 deletions src/components/BestRestaurantItem/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { BestRestaurantType } from '@/components/BestRestaurants';
import Modal from '@/components/Modal';
import SocialLogin from '@/components/Modal/SocialLogin';

import { getImageDocs } from '@/firebase/request';
import { getImageDocs, updateStarCount } from '@/firebase/request';
import Skeleton from 'react-loading-skeleton';
import 'react-loading-skeleton/dist/skeleton.css';

Expand Down Expand Up @@ -47,16 +47,24 @@ const BestRestaurantItem = ({ restaurant }: BestRestaurantItemType) => {
let favoriteArray: any = localStorage.getItem('favorite');
if (!starState) {
favoriteArray = favoriteArray === null ? [] : JSON.parse(favoriteArray);
favoriteArray.push(restaurant.id);
favoriteArray = new Set(favoriteArray);
if (favoriteArray.includes(restaurant.id)) {
setStarState(true);
return;
} else {
updateStarCount(restaurant.id, true);
favoriteArray.push(restaurant.id);
favoriteArray = new Set(favoriteArray);
}
} else {
updateStarCount(restaurant.id, false);
favoriteArray = new Set(
JSON.parse(favoriteArray).filter(
(item: any) => item !== restaurant.id,
),
);
}
favoriteArray = [...favoriteArray];

localStorage.setItem('favorite', JSON.stringify(favoriteArray));

setStarState(!starState);
Expand Down
64 changes: 31 additions & 33 deletions src/components/Header/Header.styled.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,42 +89,40 @@ export const UlContainer = styled.ul<headerprops>`
`;

export const UserLoginDiv = styled.div<headerprops>`
div {
height: 100%;
width: 86px;
display: flex;
justify-content: center;
align-items: center;
border-left: ${({ isScroll, isMain, theme }) =>
height: 100%;
width: 86px;
display: flex;
justify-content: center;
align-items: center;
border-left: ${({ isScroll, isMain, theme }) =>
isMain
? isScroll
? `1px solid ${theme.colors.gray900}`
: 'none'
: `1px solid ${theme.colors.gray900}`};

.profileImgBtn {
border: 2px solid ${({ theme }) => theme.colors.orange};
border-radius: 34px;
overflow: hidden;
width: 38px;
height: 38px;
}

button {
border: none;
color: ${({ isScroll, isMain, theme }) =>
isMain
? isScroll
? `1px solid ${theme.colors.gray900}`
: 'none'
: `1px solid ${theme.colors.gray900}`};

.profileImgBtn {
border: 2px solid ${({ theme }) => theme.colors.orange};
border-radius: 34px;
overflow: hidden;
width: 38px;
height: 38px;
}
? `${theme.colors.gray500}`
: 'white'
: `${theme.colors.gray500}`};
cursor: pointer;
background-color: transparent;

button {
border: none;
color: ${({ isScroll, isMain, theme }) =>
isMain
? isScroll
? `${theme.colors.gray500}`
: 'white'
: `${theme.colors.gray500}`};
cursor: pointer;
background-color: transparent;

img {
width: 100%;
height: 100%;
}
img {
width: 100%;
height: 100%;
}
}
`;
Expand Down
18 changes: 10 additions & 8 deletions src/components/Header/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useState, useCallback, Fragment, useEffect } from 'react';
import { useLocation, Link } from 'react-router-dom';

import { ProfileIcon, Portal, SearchBox } from '@/components';

import logo from '@/assets/img/logo.svg';

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMagnifyingGlass, faUser } from '@fortawesome/free-solid-svg-icons';
import {
Expand Down Expand Up @@ -33,10 +33,19 @@ const Header = () => {
const [isMainPage, setIsMainPage] = useState<boolean>(false);
const [scrollPosition, setScrollPosition] = useState<number>(0);

const { pathname } = useLocation();

useEffect(() => {
window.addEventListener('scroll', updateScroll);

return () => window.removeEventListener('scroll', updateScroll);
});

useEffect(() => {
setShowHeader(!(pathname === '/page-not-found'));
pathname === '/' ? setIsMainPage(true) : setIsMainPage(false);
}, [pathname]);

const onClickToggleSearchBackModal = useCallback(() => {
dispatch(modalActions.handleSearchBackModal());
}, [dispatch]);
Expand All @@ -45,8 +54,6 @@ const Header = () => {
dispatch(modalActions.handleOverlayModal());
}, [dispatch]);

const { pathname } = useLocation();

const updateScroll = () => {
setScrollPosition(window.scrollY || document.documentElement.scrollTop);
};
Expand All @@ -60,11 +67,6 @@ const Header = () => {
}
});

useEffect(() => {
setShowHeader(!(pathname === '/page-not-found'));
pathname === '/' ? setIsMainPage(true) : setIsMainPage(false);
}, [pathname]);

return (
<Fragment>
{showHeader && (
Expand Down
20 changes: 16 additions & 4 deletions src/components/ProfileIcon/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faXmark } from '@fortawesome/free-solid-svg-icons';

import { PostsWithId } from '@/firebase/type';
import { getImageDocs } from '@/firebase/request';
import { getImageDocs, updateStarCount } from '@/firebase/request';
import { useAppSelector, useAppDispatch } from '@/store/hooks';
import { modalActions } from '@/store/modal/modal-slice';

Expand All @@ -21,6 +21,7 @@ import 'react-loading-skeleton/dist/skeleton.css';
export interface ListProps extends PostsWithId {
isLiFirst: boolean;
deleteOnePost: (arg0: string) => void;
deleteOneFavorite: (arg0: string) => void;
}

const List = ({
Expand All @@ -29,10 +30,11 @@ const List = ({
address,
category,
score,
star,
star,
images,
isLiFirst,
deleteOnePost,
deleteOneFavorite,
}: ListProps) => {
const dispatch = useAppDispatch();
const { isUserLogin } = useAppSelector(({ user }) => user);
Expand All @@ -50,6 +52,7 @@ const List = ({
setIsLoadingFinish(true);
}, 600);
});
console.log(imageSrc);
}, []);

const handleSocialModal = () => {
Expand All @@ -64,14 +67,23 @@ const List = ({
let favoriteArray: any = localStorage.getItem('favorite');
if (!starState) {
favoriteArray = favoriteArray === null ? [] : JSON.parse(favoriteArray);
favoriteArray.push(id);
favoriteArray = new Set(favoriteArray);
if (favoriteArray.includes(id)) {
setStarState(true);
return;
} else {
updateStarCount(id, true);
favoriteArray.push(id);
favoriteArray = new Set(favoriteArray);
}
} else {
updateStarCount(id, false);
deleteOneFavorite(id);
favoriteArray = new Set(
JSON.parse(favoriteArray).filter((item: any) => item !== id),
);
}
favoriteArray = [...favoriteArray];

localStorage.setItem('favorite', JSON.stringify(favoriteArray));

setStarState(!starState);
Expand Down
23 changes: 22 additions & 1 deletion src/components/ProfileIcon/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
isNotSelected,
} from './ProfileIcon.styled';

import { getPostListDocs } from '@/firebase/request';
import { getPostListDocs, updateStarCount } from '@/firebase/request';
import { PostsWithId } from '@/firebase/type';
import { getAuth, signOut } from 'firebase/auth';

Expand Down Expand Up @@ -65,6 +65,16 @@ const ProfileIcon = ({
dispatch(modalActions.handleSocialModal());
};

// const renderFavoritePosts = () => {
// let favoriteArray: any = localStorage.getItem('favorite');
// favoriteArray = JSON.parse(favoriteArray);
// if (favoriteArray?.length) {
// getPostListDocs(favoriteArray).then((res) => {
// setFavoritePosts(res.reverse());
// });
// }
// };

const favoriteClick = () => {
if (isUserLogin) {
setisLiFirst(false);
Expand All @@ -86,6 +96,8 @@ const ProfileIcon = ({
const deleteOneFavorite = (postId: string) => {
let arr = favoritePosts;
arr = arr.filter((item) => item.id !== postId);

updateStarCount(postId, false);
setFavoritePosts(arr);
};

Expand All @@ -94,6 +106,13 @@ const ProfileIcon = ({
localStorage.removeItem('watched');
setRecentlyWatchedPosts([]);
} else {
let favoriteArray: any = localStorage.getItem('favorite');
favoriteArray = favoriteArray === null ? [] : JSON.parse(favoriteArray);

favoriteArray.forEach((postId: string) => {
updateStarCount(postId, false);
});

localStorage.removeItem('favorite');
setFavoritePosts([]);
}
Expand Down Expand Up @@ -157,6 +176,7 @@ const ProfileIcon = ({
images={images}
isLiFirst={isLiFirst}
deleteOnePost={deleteOneRecentlyWathced}
deleteOneFavorite={deleteOneFavorite}
></List>
);
},
Expand Down Expand Up @@ -185,6 +205,7 @@ const ProfileIcon = ({
images={images}
isLiFirst={isLiFirst}
deleteOnePost={deleteOneFavorite}
deleteOneFavorite={deleteOneFavorite}
></List>
);
},
Expand Down
18 changes: 14 additions & 4 deletions src/components/RestaurantInfo/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, MouseEvent } from 'react';
import { useParams, useNavigate } from 'react-router-dom';

import { TitleHeader, Descriptions } from './RestaurantInfo.styled';
Expand All @@ -15,6 +15,8 @@ import theme from '@/styles/theme';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { modalActions } from '@/store/modal/modal-slice';

import { updateStarCount } from '@/firebase/request';

const RestaurantInfo = () => {
const { data: post } = useAppSelector(({ restaurant }) => restaurant.post);
const navigate = useNavigate();
Expand All @@ -37,19 +39,27 @@ const RestaurantInfo = () => {

const { postId = '' } = useParams();

const changeStar = () => {
const changeStar = (e: MouseEvent) => {
if (isUserLogin) {
let favoriteArray: any = localStorage.getItem('favorite');
if (!starState) {
favoriteArray = favoriteArray === null ? [] : JSON.parse(favoriteArray);
favoriteArray.push(postId);
favoriteArray = new Set(favoriteArray);
if (favoriteArray.includes(postId)) {
setStarState(true);
return;
} else {
updateStarCount(postId, true);
favoriteArray.push(postId);
favoriteArray = new Set(favoriteArray);
}
} else {
updateStarCount(postId, false);
favoriteArray = new Set(
JSON.parse(favoriteArray).filter((item: any) => item !== postId),
);
}
favoriteArray = [...favoriteArray];

localStorage.setItem('favorite', JSON.stringify(favoriteArray));

setStarState(!starState);
Expand Down
15 changes: 15 additions & 0 deletions src/firebase/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import {
DocumentReference,
CollectionReference,
addDoc,
updateDoc,
doc,
increment,
} from 'firebase/firestore';
import { db } from '@/firebase';
import { Posts, FoodLists, Users, Reviews, DocParams } from './type';
Expand Down Expand Up @@ -89,6 +91,19 @@ export const getPostTitleDocs = async (post: string) => {
return postTitle;
};

// post id로 음식점의 star cnt 업데이트하기
export const updateStarCount = async (postId: string, isIncrement: boolean) => {
if (isIncrement) {
await updateDoc(doc(db, 'posts', postId), {
star: increment(1),
});
} else {
await updateDoc(doc(db, 'posts', postId), {
star: increment(-1),
});
}
};

// 맛집 술집 별로 데이터 가져오기(맛집 술집)
export const getTopScorePostDocs = async (num: number, category: string) => {
const q = query(
Expand Down