Skip to content

Commit

Permalink
Merge pull request #229 from FRONTENDSCHOOL5/feat/follow/#206
Browse files Browse the repository at this point in the history
[feat] follow페이지 리팩토링 #206
  • Loading branch information
jjo-mi authored Jul 30, 2023
2 parents 372fc17 + da5ae83 commit f07bea6
Show file tree
Hide file tree
Showing 4 changed files with 137 additions and 65 deletions.
2 changes: 1 addition & 1 deletion src/api/followAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const followAPI = {
const data = await response.json();
return data;
},

// 페이지 어카운트는 삭제하고자하는 상대방 계정이름을 가져와야함
async unfollowingPost(token, pageAccount) {
const response = await fetch(
`${BASE_URL}/profile/${pageAccount}/unfollow`,
Expand Down
17 changes: 13 additions & 4 deletions src/pages/Follow/Follow.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,28 @@
.followers-photo {
width: 48.81px;
height: 48.81px;
background: url(../../assets/images/profile-img42.png) no-repeat center center;
background-size: cover;
grid-column: 1 / 2;
grid-row: 1 / 3;
gap: 0;
position: relative;
cursor: pointer;
}

.followers-photo img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 50px;
}

.followers-photo-bg {
width: 100%;
height: 100%;
background: url(../../assets/images/profile-img42.png) no-repeat center center;
background-size: cover;
border-radius: 50px;
position: absolute;
top: 0;
left: 0;
}
/* 팔로워의 이름,소개,버튼을 묶은 그룹*/
.followers-inner {
margin-left: -45px;
Expand All @@ -49,6 +57,7 @@
font-weight: 700;
grid-column: 2 / 3;
grid-row: 1 / 2;
cursor: pointer;
}
/* 팔로워 소개글 */
.followers-info {
Expand Down
49 changes: 31 additions & 18 deletions src/pages/Follow/Followers/Followers.jsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import React, { useState, useEffect, useContext } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import styles from '../Follow.module.css';
import Layout from '../../../components/layout/Layout';
import { AuthContext } from '../../../context/AuthContext';
import { useParams } from 'react-router-dom';
import profileAPI from '../../../api/profileAPI2';

export default function Followings() {
const [followers, setFollowers] = useState([]);
const [buttonStates, setButtonStates] = useState([]);
const { user } = useContext(AuthContext);
const { accountname } = useParams();
const navigate = useNavigate();

useEffect(() => {
const fetchFollowers = async () => {
Expand All @@ -21,10 +22,10 @@ export default function Followings() {
setFollowers(response);
console.log('response 데이터 확인:', response);

// 각 팔로워의 초기 버튼 상태 설정
// 각 팔로워의 초기 버튼 상태 설정, api 하게 되면 필요없는 코드가 될수 있음
const initialButtonStates = new Array(response.length).fill({
text: '팔로우',
className: styles['followers-btn-follow'],
text: '삭제',
className: styles['followers-btn-unfollow'],
});
setButtonStates(initialButtonStates);
} catch (error) {
Expand All @@ -37,11 +38,14 @@ export default function Followings() {
}
}, [followers.length, accountname, user.token]);

console.log('Followers 데이터 확인:', followers);

//팔로우 삭제 버튼 들어갈 텍스트 값을 구분해주면
const updateButtonState = index => {
setButtonStates(prevStates => {
const updatedStates = [...prevStates];
updatedStates[index] = {
text: prevStates[index].text === '팔로우' ? '취소' : '팔로우',
text: prevStates[index].text === '팔로우' ? '삭제' : '팔로우',
className:
prevStates[index].className === styles['followers-btn-follow']
? styles['followers-btn-unfollow']
Expand All @@ -64,14 +68,21 @@ export default function Followings() {
className={styles.followers}
>
<div className={styles['followers-photo']}>
<img
src={follower.image}
alt="프로필 사진"
className={styles['followers-photo']}
/>
{!follower.image && (
<div className={styles['followers-photo-bg']} />
)}
{follower.image && (
<img
src={follower.image}
alt="프로필 사진"
className={styles['followers-photo-img']}
onClick={() => navigate(`/profile/${follower.accountname}`)}
/>
)}
</div>
<p
className={`${styles['followers-inner']} ${styles['followers-name']}`}
onClick={() => navigate(`/profile/${follower.accountname}`)}
>
{follower.username}
</p>
Expand All @@ -80,14 +91,16 @@ export default function Followings() {
>
{follower.intro}
</p>
<button
type="button"
id={`btn-${index}`}
className={`${styles['followers-btn']} ${buttonStates[index]?.className}`}
onClick={() => updateButtonState(index)}
>
{buttonStates[index]?.text}
</button>
{follower.accountname !== user.accountname && (
<button
type="button"
id={`btn-${index}`}
className={`${styles['followers-btn']} ${buttonStates[index]?.className}`}
onClick={() => updateButtonState(index)}
>
{buttonStates[index]?.text}
</button>
)}
</article>
))
) : (
Expand Down
134 changes: 92 additions & 42 deletions src/pages/Follow/Followings/Followings.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import React, { useState, useEffect, useContext } from 'react';
import styles from '../Follow.module.css';
import Layout from '../../../components/layout/Layout';
import { AuthContext } from '../../../context/AuthContext';
import { useParams } from 'react-router-dom';
import { useParams, useNavigate } from 'react-router-dom';
import profileAPI from '../../../api/profileAPI2';
import followAPI from '../../../api/followAPI';

export default function Followers() {
const [followers, setFollowers] = useState([]);
const [buttonStates, setButtonStates] = useState([]);
const { user } = useContext(AuthContext);
const { accountname } = useParams();
const navigate = useNavigate();

useEffect(() => {
const fetchFollowers = async () => {
Expand All @@ -23,8 +25,8 @@ export default function Followers() {

// 각 팔로워의 초기 버튼 상태 설정
const initialButtonStates = new Array(response.length).fill({
text: '팔로우',
className: styles['followers-btn-follow'],
text: '취소',
className: styles['followers-btn-unfollow'],
});
setButtonStates(initialButtonStates);
} catch (error) {
Expand All @@ -35,17 +37,52 @@ export default function Followers() {
if (followers.length === 0) {
fetchFollowers();
}
}, [followers.length, accountname, user.token]);
}, [followers, accountname, user.token]);

const updateButtonState = index => {
// 언팔로잉 api연결
const getUnfollowUser = async (followerId, selectedFollower) => {
console.log('언팔 확인중', followerId);

try {
const result = await followAPI.unfollowingPost(
user.token,
selectedFollower.accountname,
);
console.log('언팔 결과', result);
console.log('확인');

setFollowers(prevFollowers =>
prevFollowers.filter(follower => follower._id !== followerId),
);

//api 리스트를 다시 불러온다.
console.log('set 확인중', followers);
} catch (error) {
console.error('Error unfollowing user:', error);
}
};

const updateButtonState = async (index, followerId) => {
// id 뽑아내기 계정가져오는중
const selectedFollower = followers.find(
follower => follower._id === followerId,
);
console.log('선택한 구독자 정보: ', selectedFollower);

if (buttonStates[index]?.text === '취소') {
console.log('버튼 누르면 이벤트 값이 넘어와지는 확인중', followerId);
await getUnfollowUser(followerId, selectedFollower);
}

//팔로우 취소 버튼
setButtonStates(prevStates => {
const updatedStates = [...prevStates];
updatedStates[index] = {
text: prevStates[index].text === '팔로우' ? '취소' : '팔로우',
text: prevStates[index].text === '취소' ? '팔로우' : '취소',
className:
prevStates[index].className === styles['followers-btn-follow']
? styles['followers-btn-unfollow']
: styles['followers-btn-follow'],
prevStates[index].className === styles['followers-btn-unfollow']
? styles['followers-btn-follow']
: styles['followers-btn-unfollow'],
};
return updatedStates;
});
Expand All @@ -54,46 +91,59 @@ export default function Followers() {
return (
<Layout>
<h2 className="a11y-hidden">팔로워 목록</h2>
<section className={styles['followers-list']}>
<ul className={styles['followers-list']}>
{followers.length > 0 ? (
followers.map((follower, index) => (
<article
key={index}
index={index}
data={follower}
className={styles.followers}
>
<div className={styles['followers-photo']}>
<img
src={follower.image}
alt="프로필 사진"
className={styles['followers-photo']}
/>
</div>
<p
className={`${styles['followers-inner']} ${styles['followers-name']}`}
>
{follower.username}
</p>
<p
className={`${styles['followers-inner']} ${styles['followers-info']}`}
>
{follower.intro}
</p>
<button
type="button"
id={`btn-${index}`}
className={`${styles['followers-btn']} ${buttonStates[index]?.className}`}
onClick={() => updateButtonState(index)}
<li key={follower._id}>
<article
// 키값은 id로 주는게 좋고
index={index}
data={follower}
className={styles.followers}
>
{buttonStates[index]?.text}
</button>
</article>
<div className={styles['followers-photo']}>
{!follower.image && (
<div className={styles['followers-photo-bg']} />
)}
{follower.image && (
<img
src={follower.image}
alt="프로필 사진"
className={styles['followers-photo-img']}
onClick={() =>
navigate(`/profile/${follower.accountname}`)
}
></img>
)}
</div>
<p
className={`${styles['followers-inner']} ${styles['followers-name']}`}
onClick={() => navigate(`/profile/${follower.accountname}`)}
>
{follower.username}
</p>
<p
className={`${styles['followers-inner']} ${styles['followers-info']}`}
>
{follower.intro}
</p>
{follower.accountname !== user.accountname && (
<button
type="button"
id={`btn-${index}`}
className={`${styles['followers-btn']} ${buttonStates[index]?.className}`}
onClick={() => updateButtonState(index, follower._id)}
>
{buttonStates[index]?.text}
</button>
)}
</article>
</li>
))
) : (
<p>No followers found.</p>
)}
</section>
</ul>
</Layout>
);
}

0 comments on commit f07bea6

Please sign in to comment.