Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.3",
"bootstrap": "^5.3.3",
"eslint-config-react-app": "^7.0.1",
"eslint-plugin-jsx-a11y": "^6.9.0",
Expand Down
185 changes: 133 additions & 52 deletions src/components/mainPage/BestStoreList.js
Original file line number Diff line number Diff line change
@@ -1,64 +1,145 @@
import React from 'react';
import React, { useState, useEffect } from 'react';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import styles from './FoodNav.module.scss';
import { DEFAULT_IMG, imgErrorHandler } from '../../utils/error';

import styles from './FoodNav.module.scss'; // 수정된 SCSS 파일 경로
import { useModal } from '../../pages/common/ModalProvider';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faWonSign, faBoxOpen, faHeart as faHeartSolid } from "@fortawesome/free-solid-svg-icons";
import { faHeart as faHeartRegular } from "@fortawesome/free-regular-svg-icons";
import { FAVORITESTORE_URL } from '../../config/host-config';

// 하트 상태를 토글하고 서버에 저장하는 함수
const toggleFavorite = async (storeId, customerId) => {
try {
const response = await fetch(`${FAVORITESTORE_URL}/${storeId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ customerId }),
});

const contentType = response.headers.get('Content-Type');
if (contentType && contentType.includes('application/json')) {
const data = await response.json();
} else {
const text = await response.text();
console.error('⚠️Unexpected response format:', text);
}

} catch (error) {
console.error('⚠️Error toggling:', error);
}
};

// 사용자의 모든 찜 상태 조회
const fetchFavorites = async (customerId, setFavorites) => {
try {
const response = await fetch(`${FAVORITESTORE_URL}/${customerId}`);

const contentType = response.headers.get('Content-Type');
if (contentType && contentType.includes('application/json')) {
const data = await response.json();
const favorites = data.reduce((acc, store) => {
acc[store.storeId] = true;
return acc;
}, {});
setFavorites(favorites);
} else {
const text = await response.text();
console.error('⚠️Unexpected response format:', text);
}

} catch (error) {
console.error('⚠️Error fetching:', error);
}
};

const BestStoreList = ({ stores = [] }) => {
const { openModal } = useModal();
const { openModal } = useModal();
const [favorites, setFavorites] = useState({});

// customerId 더미값
const customerId = 'test@gmail.com';

useEffect(() => {
if (customerId) {
fetchFavorites(customerId, setFavorites);
}
}, [customerId]);

const handleClick = (store) => {
openModal('productDetail', { productDetail: store });
};

const handleFavoriteClick = async (storeId) => {
try {
await toggleFavorite(storeId, customerId);

const settings = {
slidesToShow: 5,
slidesToScroll: 5,
infinite: true,
arrows: true,
dots: true,
centerMode: true,
centerPadding: '0',
responsive: [
{
breakpoint: 400,
settings: {
dots: false,
slidesToShow: 2,
centerPadding: '10%',
// centerMode: false,
},
},
],
};
setFavorites(prevFavorites => ({
...prevFavorites,
[storeId]: !prevFavorites[storeId]
}));
} catch (error) {
console.error('⚠️Error toggling:', error);
}
};

const handleClick = (store) => {
openModal('productDetail', { productDetail: store });
};
const settings = {
slidesToShow: 5,
slidesToScroll: 5,
infinite: true,
arrows: true,
dots: true,
centerMode: true,
centerPadding: '0',
responsive: [
{
breakpoint: 400,
settings: {
dots: false,
slidesToShow: 2,
centerPadding: '10%',
},
},
],
};

return (
<div className={styles.list}>
<h2 className={styles.title}>추천 가게</h2>
<Slider {...settings} className={styles.slider}>
{stores.length === 0 ? (
<div>No stores available</div>
) : (
stores.map((store, index) => (
<div
key={index}
className={`${styles.storeItem} ${store.productCnt === 1 ? styles['low-stock'] : ''}`}
onClick={() => handleClick(store)}
>
<img src={store.storeImg || DEFAULT_IMG} alt={store.storeName} onError={imgErrorHandler} />
{store.productCnt === 1 && <div className={styles.overlay}>SOLD OUT</div>}
<p className={styles.storeName}>{store.storeName}</p>
<span className={styles.storePrice}>{store.price}</span>
<span className={styles.productCnt}>수량: {store.productCnt}</span>
</div>
))
)}
</Slider>
</div>
);
return (
<div className={styles.list}>
<h2 className={styles.title}>추천 가게</h2>
<Slider {...settings} className={styles.slider}>
{stores.length === 0 ? (
<div>No stores available</div>
) : (
stores.map((store, index) => (
<div
key={index}
className={`${styles.storeItem} ${store.productCnt === 1 ? styles['low-stock'] : ''}`}
>
<div
className={`${styles.heartIcon} ${favorites[store.storeId] ? styles.favorited : styles.notFavorited}`}
onClick={(e) => {
e.stopPropagation();
handleFavoriteClick(store.storeId);
}}
>
<FontAwesomeIcon
icon={favorites[store.storeId] ? faHeartSolid : faHeartRegular}
/>
</div>
<img src={store.storeImg} alt={store.storeName} />
{store.productCnt === 1 && <div className={styles.overlay}>SOLD OUT</div>}
<p className={styles.storeName}>{store.storeName}</p>
<span className={styles.storePrice}><FontAwesomeIcon icon={faWonSign} /> {store.price}</span>
<span className={styles.productCnt}><FontAwesomeIcon icon={faBoxOpen} /> 수량: {store.productCnt}</span>
</div>
))
)}
</Slider>
</div>
);
};

export default BestStoreList;
95 changes: 84 additions & 11 deletions src/components/mainPage/CategoryList.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,100 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import styles from './CategoryList.module.scss';
import { useModal } from '../../pages/common/ModalProvider';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faWonSign, faBoxOpen, faHeart as faHeartSolid } from "@fortawesome/free-solid-svg-icons";
import { faHeart as faHeartRegular } from "@fortawesome/free-regular-svg-icons";
import { DEFAULT_IMG, imgErrorHandler } from '../../utils/error';
import { FAVORITESTORE_URL } from '../../config/host-config';

// 하트 상태를 토글하고 서버에 저장하는 함수
const toggleFavorite = async (storeId, customerId) => {
try {
const response = await fetch(`${FAVORITESTORE_URL}/${storeId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// 'Authorization' : 'Bearer ' + token,
// 'refreshToken' : refreshToken
},
body: JSON.stringify({ customerId }),
});

// 응답의 Content-Type을 확인하여 JSON으로 파싱할 수 있는지 확인
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.includes('application/json')) {
const data = await response.json();
//console.log('Favorite toggled successfully!', data);
} else {
// JSON이 아닌 응답을 처리
const text = await response.text();
console.error('⚠️Unexpected response format:', text);
}

} catch (error) {
console.error('⚠️Error toggling:', error);
}
};

// 사용자의 모든 찜 상태 조회
const fetchFavorites = async (customerId, setFavorites) => {
try {
const response = await fetch(`${FAVORITESTORE_URL}/${customerId}`);

// 응답의 Content-Type을 확인하여 JSON으로 파싱할 수 있는지 확인
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.includes('application/json')) {
const data = await response.json();
const favorites = data.reduce((acc, store) => {
acc[store.storeId] = true;
return acc;
}, {});
setFavorites(favorites);
} else {
// JSON이 아닌 응답을 처리
const text = await response.text();
console.error('⚠️Unexpected response format:', text);
}

} catch (error) {
console.error('⚠️Error fetching:', error);
}
};





const CategoryList = ({ stores }) => {
const { openModal } = useModal();
const [favorites, setFavorites] = useState({}); // 찜 상태를 관리할 객체
const [favorites, setFavorites] = useState({});

// customerId 더미값
const customerId = 'test@gmail.com';

const handleClick = (store) => {
openModal('productDetail', { productDetail: store });
};

const handleFavoriteClick = (storeId) => {
setFavorites(prevFavorites => ({
...prevFavorites,
[storeId]: !prevFavorites[storeId]
}));
const handleFavoriteClick = async (storeId) => {
try {
await toggleFavorite(storeId, customerId);

// 찜 상태를 토글
setFavorites(prevFavorites => ({
...prevFavorites,
[storeId]: !prevFavorites[storeId]
}));
} catch (error) {
console.error('⚠️Error toggling:', error);
}
};

useEffect(() => {
if (customerId) {
fetchFavorites(customerId, setFavorites);
}
}, [customerId]);

return (
<div className={styles.list}>
<h1 className={styles.storeList}>우리 동네 가게 리스트</h1>
Expand All @@ -32,18 +106,17 @@ const CategoryList = ({ stores }) => {
onClick={() => handleClick(store)}
>
<div
className={styles.heartIcon}
className={`${styles.heartIcon} ${favorites[store.storeId] ? styles.favorited : styles.notFavorited}`}
onClick={(e) => {
e.stopPropagation();
handleFavoriteClick(store.storeId);
}}
>
<FontAwesomeIcon
icon={favorites[store.storeId] ? faHeartSolid : faHeartRegular}
className={favorites[store.storeId] ? styles.favorited : styles.notFavorited}
/>
</div>
<img src={store.storeImg || DEFAULT_IMG} alt={store.storeName} className={styles.categoryImage} onError={imgErrorHandler} />
<img src={store.storeImg} alt={store.storeName} className={styles.categoryImage} />
{store.productCnt === 1 && <div className={styles.overlay}>SOLD OUT</div>}
<p className={styles.categoryName}>{store.storeName}</p>

Expand Down
Loading