Skip to content

Commit

Permalink
Refactor 저장 데이터 분리
Browse files Browse the repository at this point in the history
Refactor 버전과 데이터 상태 분리

Refactor 커스텀 훅 이름 변경

Refactor 데이터, 버전 활용 분기점 설정

Fix 새로 고침할 때, 인증 상태 활용

Feat 버전 튜토리얼

Type 버전 상태

Style 나만의 공간 데이터 위치 조정

Refactor 불필요한 토스트 알림 방지
  • Loading branch information
whoisrey committed Dec 20, 2024
1 parent 33018df commit 52a0e7a
Show file tree
Hide file tree
Showing 15 changed files with 241 additions and 155 deletions.
7 changes: 5 additions & 2 deletions src/components/AuthPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { loginUser, logoutUser } from "../services/authService";
import useAuthStore from "../stores/useAuthStore";
import useModalStore from "../stores/useModalStore";
import useDataStore from "../stores/useDataStore";
import useVersionStore from "../stores/useVersionStore";

import {
AuthPanelContainer,
Expand All @@ -23,7 +24,8 @@ import {

const AuthPanel = () => {
const { isLoggedIn, setIsLoggedIn } = useAuthStore();
const { setUserId, setUserData, setCurrentIndex } = useDataStore();
const { setUserId, setUserData } = useDataStore();
const { setUserVersion, setVersionIndex } = useVersionStore();
const { modals, closeModal } = useModalStore();

const handleLogin = async () => {
Expand Down Expand Up @@ -52,7 +54,8 @@ const AuthPanel = () => {
setIsLoggedIn(false);
setUserId(null);
setUserData([]);
setCurrentIndex(0);
setUserVersion([]);
setVersionIndex(0);
} catch (logoutError) {
toast.error("로그아웃을 다시 시도해주세요.");
console.error("로그아웃 에러가 발생하였습니다:", logoutError);
Expand Down
11 changes: 4 additions & 7 deletions src/components/Gallery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,15 @@ import {
} from "../style/GalleryStyle";

import type { UserData } from "../types/common";
import type { GalleryProps } from "../types/components";
import { useState } from "react";

const Gallery = ({ data }: GalleryProps) => {
const Gallery = () => {
const [positionIdToDelete, setPositionIdToDelete] = useState(null);

const { userData, setUserData } = useDataStore();
const { modals, openModal, closeModal } = useModalStore();
const { setModelPositions, setModelRotations } = useModelStore();

const filteredUserData = userData.filter((item) => item.name);

const handleOpenDeleteModal = (item: UserData) => {
setPositionIdToDelete(item.positionId);
openModal("deleteModal");
Expand Down Expand Up @@ -64,7 +61,7 @@ const Gallery = ({ data }: GalleryProps) => {

toast.success("삭제되었습니다.");
} catch (deleteError) {
setUserData(data);
setUserData(userData);

closeModal("deleteModal");

Expand All @@ -76,7 +73,7 @@ const Gallery = ({ data }: GalleryProps) => {
return (
<DataListContainer>
<DataList>
{filteredUserData.length !== 0 && (
{userData.length !== 0 && (
<thead>
<tr>
<th>이름</th>
Expand All @@ -85,7 +82,7 @@ const Gallery = ({ data }: GalleryProps) => {
</thead>
)}
<tbody>
{filteredUserData.map((item) => (
{userData.map((item) => (
<DataListRow key={item.positionId}>
<DataListCell>{item.name}</DataListCell>
<DataListCell className="button-container">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,23 @@ import useModelStore from "../stores/useModelStore";
import { isDuplicateData } from "../utils/validators";

import type { UserData } from "../types/common";
import useVersionStore from "../stores/useVersionStore";

const useAutoSavePosition = (delay: number): null => {
const useAutoSaveVersion = (delay: number): null => {
const timeoutRef = useRef(null);

const { isLoggedIn } = useAuthStore();
const { userId, userData, setUserData } = useDataStore();
const { isLoggedIn, isAuthChecked } = useAuthStore();
const { userId } = useDataStore();
const { userVersion, setUserVersion } = useVersionStore();
const { modals } = useModalStore();
const { positions, rotations } = useModelStore();

const isDuplicate = isDuplicateData(userData, positions, rotations);
const isDuplicate = isDuplicateData(userVersion, positions, rotations);
const openSaveModal = modals.saveModal;

const saveChanges = async () => {
const positionId = uuidv4();
const newUserData: UserData = {
const newVersion: UserData = {
userId,
positionId,
firstSpeakerPosition: positions.firstSpeaker,
Expand All @@ -39,8 +41,8 @@ const useAutoSavePosition = (delay: number): null => {

if (isLoggedIn) {
try {
setUserData([...userData, newUserData]);
await saveUserPosition(userId, newUserData);
setUserVersion([...userVersion, newVersion]);
await saveUserPosition(userId, newVersion);

toast.success("자동 저장되었습니다!");
} catch (autoSaveError) {
Expand All @@ -50,10 +52,10 @@ const useAutoSavePosition = (delay: number): null => {
} else {
try {
localStorage.setItem(
"savedUserData",
JSON.stringify([...userData, newUserData]),
"localData",
JSON.stringify([...userVersion, newVersion]),
);
setUserData([...userData, newUserData]);
setUserVersion([...userVersion, newVersion]);

toast.success("자동 저장되었습니다!");
} catch (autoSaveError) {
Expand All @@ -67,7 +69,7 @@ const useAutoSavePosition = (delay: number): null => {
};

useEffect(() => {
if (openSaveModal) {
if (!isAuthChecked || openSaveModal) {
return;
}

Expand All @@ -87,4 +89,4 @@ const useAutoSavePosition = (delay: number): null => {
return null;
};

export default useAutoSavePosition;
export default useAutoSaveVersion;
20 changes: 10 additions & 10 deletions src/hooks/useKeyboardEvent.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { useState, useEffect } from "react";
import { toast } from "react-toastify";

import useDataStore from "../stores/useDataStore";
import useModeStore from "../stores/useModeStore";
import useVersionStore from "../stores/useVersionStore";

const useKeyboardEvent = () => {
const { userData, currentIndex, setCurrentIndex } = useDataStore();
const { userVersion, versionIndex, setVersionIndex } = useVersionStore();
const { switchMode } = useModeStore();

const [isShiftPressed, setIsShiftPressed] = useState(false);
const userDataLength = userData.length;
const userVersionLength = userVersion.length;

const handleModeSwitch = (key: string) => {
switch (key) {
Expand All @@ -28,20 +28,20 @@ const useKeyboardEvent = () => {
};

const handleDataNavigation = (key: string) => {
const isInitialIndex = currentIndex === 0;
const isLastIndex = currentIndex === userDataLength - 1;
const isInitialIndex = versionIndex === 0;
const isLastIndex = versionIndex === userVersionLength - 1;

if (key === "z" || key === "ㅋ") {
if (isInitialIndex) {
toast.info("처음입니다.");
toast.info("처음 버전입니다.");
} else {
setCurrentIndex(currentIndex - 1);
setVersionIndex(versionIndex - 1);
}
} else if (key === "x" || key === "ㅌ") {
if (isLastIndex) {
toast.info("마지막입니다.");
toast.info("마지막 버전입니다.");
} else {
setCurrentIndex(currentIndex + 1);
setVersionIndex(versionIndex + 1);
}
}
};
Expand Down Expand Up @@ -91,7 +91,7 @@ const useKeyboardEvent = () => {
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("keyup", handleKeyUp);
};
}, [currentIndex, userDataLength]);
}, [versionIndex, userVersion]);

return { isShiftPressed };
};
Expand Down
28 changes: 0 additions & 28 deletions src/hooks/useNavigateData.tsx

This file was deleted.

29 changes: 29 additions & 0 deletions src/hooks/useNavigateVersion.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useEffect } from "react";

import useModelStore from "../stores/useModelStore";
import useVersionStore from "../stores/useVersionStore";

const useNavigateVersion = (): null => {
const { userVersion, versionIndex } = useVersionStore();
const { setModelPositions, setModelRotations } = useModelStore();

const hasUserVersion = userVersion.length > 0;
const isCorrectIndex = versionIndex >= 0 && versionIndex < userVersion.length;

useEffect(() => {
if (hasUserVersion && isCorrectIndex) {
const currentVersion = userVersion[versionIndex];

setModelPositions("firstSpeaker", currentVersion.firstSpeakerPosition);
setModelPositions("secondSpeaker", currentVersion.secondSpeakerPosition);
setModelPositions("listener", currentVersion.listenerPosition);
setModelRotations("firstSpeaker", currentVersion.firstSpeakerRotation);
setModelRotations("secondSpeaker", currentVersion.secondSpeakerRotation);
setModelRotations("listener", currentVersion.listenerRotation);
}
}, [versionIndex, userVersion]);

return null;
};

export default useNavigateVersion;
60 changes: 34 additions & 26 deletions src/hooks/useUpdateData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,30 @@ import { getUserPosition, saveUserPosition } from "../services/userService";

import useAuthStore from "../stores/useAuthStore";
import useDataStore from "../stores/useDataStore";
import useVersionStore from "../stores/useVersionStore";

import { isSameData } from "../utils/validators";

import { UserData } from "../types/common";

const useUpdateData = (): null => {
const { setIsLoggedIn } = useAuthStore();
const { setUserId, setUserData, setCurrentIndex } = useDataStore();
const { setIsLoggedIn, setIsAuthChecked } = useAuthStore();
const { setUserId, setUserData } = useDataStore();
const { setUserVersion, setVersionIndex } = useVersionStore();

const getLocalData = () => {
const savedData = localStorage.getItem("savedUserData");
const savedData = localStorage.getItem("localData");
return savedData ? JSON.parse(savedData) : [];
};

const updateLocalData = () => {
const savedLocalData = getLocalData();
const localVersion = getLocalData();

if (savedLocalData.length > 0) {
setUserData(savedLocalData);
if (localVersion.length > 0) {
setUserVersion(localVersion);
} else {
setUserData([]);
setCurrentIndex(0);
setUserVersion([]);
setVersionIndex(0);
}
};

Expand All @@ -45,8 +47,10 @@ const useUpdateData = (): null => {
setUserId(user.uid);
updateUserData(user);
} else {
setIsLoggedIn(false);
updateLocalData();
}
setIsAuthChecked(true);
});

return () => unsubscribe();
Expand All @@ -55,43 +59,47 @@ const useUpdateData = (): null => {
const updateUserData = async (user: User) => {
try {
const response = await getUserPosition();
const savedUserData = response.user;
const savedUserData = response.user.filter((item) => item.name);
const savedUserVersion = response.user.filter((item) => !item.name);

const savedLocalData = getLocalData();
const localVersion = getLocalData();

const previousData = [...savedUserData];
const previousVersion = [...savedUserVersion];

const uniqueData = filterUniqueData(savedUserData, savedLocalData).map(
(data) => ({
...data,
userId: user.uid,
}),
);
const mergedData = [...savedUserData, ...uniqueData];

setUserData(mergedData);
const uniqueVersion = filterUniqueData(
savedUserVersion,
localVersion,
).map((data) => ({
...data,
userId: user.uid,
}));
const mergedVersion = [...savedUserVersion, ...uniqueVersion];
setUserVersion(mergedVersion);
setUserData(savedUserData);

try {
await Promise.all(
uniqueData.map((data) => saveUserPosition(user.uid, data)),
uniqueVersion.map((data) => saveUserPosition(user.uid, data)),
);

if (uniqueData.length > 0) {
if (uniqueVersion.length > 0) {
toast.success("동기화에 성공하였습니다.");
}

localStorage.removeItem("savedUserData");
localStorage.removeItem("localData");
} catch (updateError) {
setUserData(previousData);
setUserVersion(previousVersion);

toast.error("동기화에 실패하였습니다.");
console.error("동기화에 실패하였습니다: ", updateError);
}
} catch (fetchError) {
setIsLoggedIn(false);

toast.error("로그인을 다시 시도해주세요.");
console.error("데이터를 가져오는데 실패하였습니다:", fetchError);
if (auth.currentUser) {
toast.error("로그인을 다시 시도해주세요.");
console.error("데이터를 가져오는데 실패하였습니다:", fetchError);
}
}
};

Expand Down
6 changes: 1 addition & 5 deletions src/pages/GalleryPage.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import NavHeader from "../components/common/NavHeader";
import Gallery from "../components/Gallery";

import useDataStore from "../stores/useDataStore";

import { GalleryPageContainer } from "../style/GalleryPageStyle";

const GalleryPage = () => {
const { userData } = useDataStore();

return (
<GalleryPageContainer>
<NavHeader />
<Gallery data={userData} />
<Gallery />
</GalleryPageContainer>
);
};
Expand Down
Loading

0 comments on commit 52a0e7a

Please sign in to comment.