Skip to content

Commit

Permalink
Merge pull request #74 from TU-GitLio/fix/#73
Browse files Browse the repository at this point in the history
fix: data missing issue when refresh
  • Loading branch information
POL6463 authored Jun 20, 2024
2 parents c206517 + 0403f90 commit 12c5941
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 76 deletions.
71 changes: 45 additions & 26 deletions gitlio/app/editor/[portfolioId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,66 @@ import { useRouter } from 'next/navigation';
import { useUserStore } from '@/store/userStore';
import useModalStore from '@/store/modalStore';
import ShareModal from '../_components/ShareModal';
import { useUser } from '@clerk/nextjs';
import { fetchPortfolios, fetchUserId } from '@/services/userServices';

interface EditPageProps {
params: {
portfolioId: string;
};
}
export default function EditPage({ params }: EditPageProps) {
const { isSignedIn, user, isLoaded } = useUser();
const [isLoading, setIsLoading] = useState(true); // State to manage loading
const { isOpen, closeModal } = useModalStore();
const router = useRouter();
const { portfolios, setCurrentPortfolio } = useUserStore((state) => ({
portfolios: state.portfolios,
setCurrentPortfolio: state.setCurrentPortfolio,
}));
const { portfolios, setCurrentPortfolio, currentPortfolio } = useUserStore(
(state) => ({
portfolios: state.portfolios,
setCurrentPortfolio: state.setCurrentPortfolio,
currentPortfolio: state.currentPortfolio,
})
);
const { portfolioId } = params;

console.log(params);
useEffect(() => {
const fetchPortfolioData = async () => {
const portfolio = portfolios.find(
(portfolio) => portfolio.portfolio_id.toString() === portfolioId
);

//if (!portfolio) {
//router.push('/error'); // Redirect to an error page if the portfolio ID is not found
//return;
//}
//일치하는 포트폴리오 찾았으면 현재 포트폴리오로 세팅
setCurrentPortfolio(portfolio);

try {
await updateStoresWithPortfolioData(portfolioId);
setIsLoading(false);
} catch (error) {
console.error('Failed to update stores:', error);
setIsLoading(false);
// 이 useEffect는 컴포넌트 마운트 시 한 번만 실행됩니다.
console.log(
'initializeData 실행 중...' + isSignedIn + user + portfolios.length
);
async function initializeData() {
if (isSignedIn && user && portfolios.length === 0) {
const fetchedUserId = await fetchUserId(user);
if (fetchedUserId) {
await fetchPortfolios();
}
}
};
}
initializeData();
}, [isLoaded]); // isLoaded를 종속성에서 제거

fetchPortfolioData();
}, [portfolioId, portfolios, router, setCurrentPortfolio]);
useEffect(() => {
// 포트폴리오 상태 감시
if (portfolios.length > 0) {
const selectedPortfolio = portfolios.find(
(p) => p.portfolio_id.toString() === portfolioId
);
if (!selectedPortfolio) {
console.log('포트폴리오를 찾을 수 없습니다.');
return;
}
setCurrentPortfolio(selectedPortfolio);
(async () => {
try {
await updateStoresWithPortfolioData(portfolioId);
setIsLoading(false);
} catch (error) {
console.error('Failed to update stores:', error);
setIsLoading(false);
}
})();
}
}, [portfolios, portfolioId]); // 포트폴리오 배열과 포트폴리오 ID에 의존

const setSelectedSection = useSidebarStore(
(state) => state.setSelectedSection
Expand Down
57 changes: 7 additions & 50 deletions gitlio/app/studio/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,73 +1,30 @@
'use client';
import React, { useEffect, useState, useRef } from 'react';
import { useUser } from '@clerk/nextjs';
import { useUserStore } from '@/store/userStore';
import { getIdAfterLogin, getUserPortfolios } from '@/actions/user';
import PortfolioComponent from '@/components/PortfolioComponent';
import { useRouter } from 'next/navigation';
import PortfolioSkeleton from '@/components/PortfolioSkeleton';
import { fetchPortfolios, fetchUserId } from '@/services/userServices';

export default function DashboardPage() {
const { isSignedIn, user, isLoaded } = useUser();
const { setUser, setUserId, setPortfolios } = useUserStore((state) => ({
setUser: state.setUser,
setUserId: state.setUserId,
setPortfolios: state.setPortfolios,
}));
const userId = useUserStore((state) => state.userId);
const [loading, setLoading] = useState(true);
const router = useRouter();
if (isLoaded && !isSignedIn) {
router.push('/');
}

useEffect(() => {
// 사용자 ID를 가져오는 과정
const fetchUserId = async () => {
if (user && user.id && !userId) {
try {
const fetchedUserId: number = await getIdAfterLogin({
clerk_id: user.id,
email: user.emailAddresses[0]?.emailAddress,
name: user.fullName,
if (isSignedIn && user) {
fetchUserId(user).then((fetchedUserId) => {
if (fetchedUserId) {
fetchPortfolios().finally(() => {
setLoading(false);
});
setUserId(fetchedUserId);
return fetchedUserId; // 다음 단계에서 사용할 수 있도록 fetchedUserId를 반환합니다.
} catch (err) {
console.error('Failed to fetch userId:', err);
}
}
return null;
};

// 포트폴리오 목록을 가져오는 과정
const fetchPortfolios = async (id: null | number) => {
if (!id) return; // userId가 없다면 실행하지 않음
try {
const portfolios = await getUserPortfolios(id.toString());
console.log(portfolios);
if (Array.isArray(portfolios)) {
setPortfolios(portfolios);
setLoading(false);
} else {
console.error(
'Expected an array of portfolios, received:',
portfolios
);
setPortfolios([]);
}
} catch (err) {
console.error('Failed to fetch portfolios:', err);
}
};

if (isSignedIn) {
fetchUserId().then((fetchedUserId) => {
// UserID를 성공적으로 가져왔다면, 포트폴리오를 불러옴
fetchPortfolios(fetchedUserId || userId);
});
}
}, [isSignedIn, user, userId]); // 의존성 배열을 최적화하여 필요한 변수들만 포함시킴
}, [isLoaded]);

if (loading) {
return <PortfolioSkeleton />;
Expand Down
45 changes: 45 additions & 0 deletions gitlio/services/userServices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { getIdAfterLogin, getUserPortfolios } from '@/actions/user';
import { useUserStore } from '@/store/userStore';
import { useUser } from '@clerk/nextjs';

// Zustand 스토어 사용 설정
const { setUserId, setPortfolios } = useUserStore.getState();

// 사용자 ID를 가져오는 함수
export const fetchUserId = async (user: any) => {
if (user && user.id) {
const existingUserId = useUserStore.getState().userId;
if (!existingUserId) {
try {
const fetchedUserId: number = await getIdAfterLogin({
clerk_id: user.id,
email: user.emailAddresses[0]?.emailAddress,
name: user.fullName,
});
setUserId(fetchedUserId);
return fetchedUserId; // 다음 단계에서 사용할 수 있도록 fetchedUserId를 반환합니다.
} catch (err) {}
} else {
return existingUserId;
}
}
return null;
};

// 포트폴리오 목록을 가져오는 함수
export const fetchPortfolios = async () => {
const id = useUserStore.getState().userId;
if (!id) return; // userId가 없다면 실행하지 않음
try {
const portfolios = await getUserPortfolios(id.toString());
console.log(portfolios);
if (Array.isArray(portfolios)) {
setPortfolios(portfolios);
} else {
console.error('Expected an array of portfolios, received:', portfolios);
setPortfolios([]);
}
} catch (err) {
console.error('Failed to fetch portfolios:', err);
}
};

0 comments on commit 12c5941

Please sign in to comment.