From 36c3f6e37342020557897925a2c2980725fc56d7 Mon Sep 17 00:00:00 2001 From: suyeonnnnnnn Date: Tue, 14 Nov 2023 02:59:35 +0900 Subject: [PATCH 1/7] Feat: Add UserConfigModal --- src/components/Login/SignUpModal/index.tsx | 7 +- src/components/Main/UserConfigModal/index.tsx | 298 +++++++++++++++++- src/pages/Main/user/index.tsx | 21 +- 3 files changed, 318 insertions(+), 8 deletions(-) diff --git a/src/components/Login/SignUpModal/index.tsx b/src/components/Login/SignUpModal/index.tsx index 764e4566..aa0f083b 100644 --- a/src/components/Login/SignUpModal/index.tsx +++ b/src/components/Login/SignUpModal/index.tsx @@ -72,10 +72,9 @@ const SignUpModal = ({ isOpen, onClose }: SignUpModalProps) => { // ID 중복 검사 const checkIdDuplication = async (id: string): Promise => { try { - const response = await axios.post( - "https://fastcampus-chat.net/check/id", - { id }, - ); + const response = await axios.post("https://fastcampus-chat.net/auth/id", { + id, + }); return response.data.isDuplicated; } catch (error) { console.error("Error checking ID duplication", error); diff --git a/src/components/Main/UserConfigModal/index.tsx b/src/components/Main/UserConfigModal/index.tsx index 01bde8f4..c3f3fec3 100644 --- a/src/components/Main/UserConfigModal/index.tsx +++ b/src/components/Main/UserConfigModal/index.tsx @@ -1,5 +1,299 @@ -const UserConfigModal = () => { - return
user config modal
; +import React, { useCallback, useRef, useState, useEffect } from "react"; +import { useForm, Controller } from "react-hook-form"; +import { + Input, + Button, + Alert, + AlertIcon, + Modal, + ModalOverlay, + ModalContent, + ModalCloseButton, + ModalBody, + FormControl, + FormErrorMessage, + Box, + Image, + Text, +} from "@chakra-ui/react"; +import { useRecoilValue } from "recoil"; +import { authState } from "../../../recoil/atoms/authState"; +import axios from "axios"; +import styled from "styled-components"; +import { FaImage } from "react-icons/fa"; +import useFetch from "../../../hooks/useFetch"; + +const MAX_IMAGE_SIZE = 1024 * 1024; // 1MB + +interface FormData { + id: string; + name: string; + picture?: string; +} + +const DragDropBox = styled(Box)` + border: 3px dashed #dbdbdb; + position: relative; + width: 40%; + height: 140px; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + cursor: pointer; + margin-top: 40px; + margin-bottom: 40px; + margin-left: auto; + margin-right: auto; +`; + +interface UserConfigModalProps { + isOpen: boolean; + onClose: () => void; +} + +const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { + const auth = useRecoilValue(authState); + const [selectedFile, setSelectedFile] = useState(null); + const [profile, setProfile] = useState({ + id: "", + name: "", + picture: "", + }); + const fileInputRef = useRef(null); + const [updateStatus, setUpdateStatus] = useState<{ + type: "success" | "error"; + message: string; + } | null>(null); + + const { + control, + handleSubmit, + setValue, + setError, + clearErrors, + formState: { errors }, + } = useForm(); + + // 사용자 정보를 가져오기. + const { result: userInfo, refresh: refreshUserInfo } = useFetch({ + url: "https://fastcampus-chat.net/auth/me", // 사용자 정보를 가져오는 URL + method: "GET", + start: isOpen, // 모달이 열릴 때 요청 시작 + }); + + useEffect(() => { + if (userInfo && userInfo.auth) { + console.log("UserInfo:", userInfo); // 로깅 추가 + setValue("id", userInfo.user.id); + setValue("name", userInfo.user.name); + setValue("picture", userInfo.user.picture); + } + }, [userInfo, setValue, isOpen]); + + // ID 중복 검사 + const checkIdDuplication = async (id: string): Promise => { + try { + const response = await axios.post("https://fastcampus-chat.net/auth/me", { + id, + }); + return response.data.isDuplicated; + } catch (error) { + console.error("Error checking ID duplication", error); + return false; + } + }; + + // 파일 선택 변경 + const handleFileChange = (event: React.ChangeEvent) => { + const file = event.target.files ? event.target.files[0] : null; + if (file) { + if (file.size > MAX_IMAGE_SIZE) { + // 파일 크기 초과 에러 처리 + alert("이미지는 1MB 이하이어야 합니다."); + return; + } + setSelectedFile(file); + } + }; + + // 드래그 앤 드롭 + const onDrop = useCallback((event: React.DragEvent) => { + event.preventDefault(); + const file = event.dataTransfer.files[0]; + if (file) { + setSelectedFile(file); + } + }, []); + + const onDragOver = useCallback((event: React.DragEvent) => { + event.preventDefault(); + }, []); + + // 파일 입력 필드 트리거 + const triggerFileSelect = () => { + fileInputRef.current?.click(); + }; + + // 사용자 정보 업데이트 + const updateUserInfo = useFetch({ + url: "https://fastcampus-chat.net/user", + method: "PATCH", + data: {}, + start: false, + }); + + // 프로필 수정 제출 + const onSubmit = async (formData: FormData) => { + const toBase64 = (file: File) => + new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.readAsDataURL(file); + reader.onload = () => resolve(reader.result as string); + reader.onerror = (error) => reject(error); + }); + + const updatedData = { + name: formData.name, + picture: selectedFile ? await toBase64(selectedFile) : profile.picture, + }; + + try { + updateUserInfo.refresh({ data: updatedData }); // 데이터 업데이트 요청 + + // 결과 확인 + if (updateUserInfo.statusCode === 200) { + setUpdateStatus({ + type: "success", + message: "프로필이 업데이트 되었습니다.", + }); + } + } catch (error) { + setUpdateStatus({ + type: "error", + message: "프로필 업데이트에 실패했습니다.", + }); + console.error("프로필 업데이트 실패:", error); + } + }; + + return ( + + + + + + {updateStatus && ( + + + {updateStatus.message} + + )} + {/* 회원가입 폼 */} +
+ + {selectedFile ? ( + Upload Preview + ) : ( + + )} + 이미지 업로드 + + + {/* 아이디 입력 */} + + { + try { + const isDuplicated = await checkIdDuplication(id); + if (isDuplicated) { + setError("id", { + type: "manual", + message: "이미 사용중인 ID입니다.", + }); + return false; + } + clearErrors("id"); + return true; + } catch (error) { + console.error("ID 중복 확인 중 오류 발생:", error); + return "ID 중복 확인 중 오류가 발생했습니다."; + } + }, + }} + render={({ field }) => ( + + )} + /> + + {errors.id && errors.id.message} + + + {/* 닉네임 입력 */} + + ( + + )} + /> + + {errors.name && errors.name.message} + + + +
+
+
+
+ ); }; export default UserConfigModal; diff --git a/src/pages/Main/user/index.tsx b/src/pages/Main/user/index.tsx index e9c0388a..654479e1 100644 --- a/src/pages/Main/user/index.tsx +++ b/src/pages/Main/user/index.tsx @@ -4,6 +4,8 @@ import { authState } from "../../../recoil/atoms/authState"; import { useAuth } from "../../../hooks/useAuth"; import { userState } from "../../../recoil/atoms/userState"; import { useNavigate } from "react-router-dom"; +import { useState } from "react"; +import UserConfigModal from "../../../components/Main/UserConfigModal"; const AdminMain = () => { console.log("AdminMain 렌더링"); // 컴포넌트 렌더링 확인 @@ -12,21 +14,36 @@ const AdminMain = () => { const { logout } = useAuth(); const navigate = useNavigate(); const user = useRecoilValue(userState); // Recoil의 userState를 통해 사용자 정보 확인 + const [isUserConfigModalOpen, setIsUserConfigModalOpen] = useState(false); + + const toggleUserConfigModal = () => { + setIsUserConfigModalOpen(!isUserConfigModalOpen); + }; + const handleLogout = () => { logout(); navigate("/"); }; + console.log("User ID:", user.id); if (isAuthenticated) { return (
사용자 ID: {user.id}
+ + {isUserConfigModalOpen && ( + + )} + {/* */}
); } - - return
admin main page
; }; export default AdminMain; From abe81859066a8a2a75863ef4793f7beba36bc1ea Mon Sep 17 00:00:00 2001 From: suyeonnnnnnn Date: Tue, 14 Nov 2023 03:11:35 +0900 Subject: [PATCH 2/7] Feat: Add image in UserConfigModal --- src/components/Main/UserConfigModal/index.tsx | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/components/Main/UserConfigModal/index.tsx b/src/components/Main/UserConfigModal/index.tsx index c3f3fec3..c4118970 100644 --- a/src/components/Main/UserConfigModal/index.tsx +++ b/src/components/Main/UserConfigModal/index.tsx @@ -88,8 +88,14 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { setValue("id", userInfo.user.id); setValue("name", userInfo.user.name); setValue("picture", userInfo.user.picture); + setProfile({ + ...profile, + id: userInfo.user.id, + name: userInfo.user.name, + picture: userInfo.user.picture, + }); } - }, [userInfo, setValue, isOpen]); + }, [userInfo, setValue, setProfile, isOpen]); // ID 중복 검사 const checkIdDuplication = async (id: string): Promise => { @@ -211,6 +217,12 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { alt="Upload Preview" boxSize="40px" /> + ) : profile.picture ? ( + Profile Picture ) : ( )} From 4144bb044f76598812b0909df63eb6744b11458d Mon Sep 17 00:00:00 2001 From: suyeonnnnnnn Date: Tue, 14 Nov 2023 11:58:00 +0900 Subject: [PATCH 3/7] Feat: Add user profile update --- src/components/Main/UserConfigModal/index.tsx | 114 +++++------------- 1 file changed, 33 insertions(+), 81 deletions(-) diff --git a/src/components/Main/UserConfigModal/index.tsx b/src/components/Main/UserConfigModal/index.tsx index c4118970..3977d863 100644 --- a/src/components/Main/UserConfigModal/index.tsx +++ b/src/components/Main/UserConfigModal/index.tsx @@ -52,6 +52,7 @@ interface UserConfigModalProps { onClose: () => void; } +// 프로필 설정 모달 const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { const auth = useRecoilValue(authState); const [selectedFile, setSelectedFile] = useState(null); @@ -70,26 +71,25 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { control, handleSubmit, setValue, - setError, - clearErrors, formState: { errors }, } = useForm(); - // 사용자 정보를 가져오기. - const { result: userInfo, refresh: refreshUserInfo } = useFetch({ - url: "https://fastcampus-chat.net/auth/me", // 사용자 정보를 가져오는 URL + // 사용자 정보 가져오기. + const { result: userInfo } = useFetch({ + url: "https://fastcampus-chat.net/auth/me", method: "GET", start: isOpen, // 모달이 열릴 때 요청 시작 }); + // 사용자 정보를 폼에 설정 useEffect(() => { if (userInfo && userInfo.auth) { - console.log("UserInfo:", userInfo); // 로깅 추가 + console.log("UserInfo:", userInfo); + // 폼 값 설정 로직 setValue("id", userInfo.user.id); setValue("name", userInfo.user.name); setValue("picture", userInfo.user.picture); setProfile({ - ...profile, id: userInfo.user.id, name: userInfo.user.name, picture: userInfo.user.picture, @@ -97,19 +97,6 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { } }, [userInfo, setValue, setProfile, isOpen]); - // ID 중복 검사 - const checkIdDuplication = async (id: string): Promise => { - try { - const response = await axios.post("https://fastcampus-chat.net/auth/me", { - id, - }); - return response.data.isDuplicated; - } catch (error) { - console.error("Error checking ID duplication", error); - return false; - } - }; - // 파일 선택 변경 const handleFileChange = (event: React.ChangeEvent) => { const file = event.target.files ? event.target.files[0] : null; @@ -141,14 +128,6 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { fileInputRef.current?.click(); }; - // 사용자 정보 업데이트 - const updateUserInfo = useFetch({ - url: "https://fastcampus-chat.net/user", - method: "PATCH", - data: {}, - start: false, - }); - // 프로필 수정 제출 const onSubmit = async (formData: FormData) => { const toBase64 = (file: File) => @@ -163,23 +142,34 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { name: formData.name, picture: selectedFile ? await toBase64(selectedFile) : profile.picture, }; - try { - updateUserInfo.refresh({ data: updatedData }); // 데이터 업데이트 요청 - - // 결과 확인 - if (updateUserInfo.statusCode === 200) { + // axios 요청 및 응답 처리 + const response = await axios.patch( + "https://fastcampus-chat.net/user", + updatedData, + { + headers: { + "content-type": "application/json", + Authorization: `Bearer ${auth.accessToken}`, + }, + }, + ); + if (response.status === 200) { setUpdateStatus({ type: "success", message: "프로필이 업데이트 되었습니다.", }); + } else { + setUpdateStatus({ + type: "error", + message: "프로필 업데이트에 실패했습니다. ", + }); } } catch (error) { setUpdateStatus({ type: "error", message: "프로필 업데이트에 실패했습니다.", }); - console.error("프로필 업데이트 실패:", error); } }; @@ -204,7 +194,7 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { {updateStatus.message} )} - {/* 회원가입 폼 */} + {/* 프로필 폼 */}
{ {/* 아이디 입력 */} - { - try { - const isDuplicated = await checkIdDuplication(id); - if (isDuplicated) { - setError("id", { - type: "manual", - message: "이미 사용중인 ID입니다.", - }); - return false; - } - clearErrors("id"); - return true; - } catch (error) { - console.error("ID 중복 확인 중 오류 발생:", error); - return "ID 중복 확인 중 오류가 발생했습니다."; - } - }, - }} - render={({ field }) => ( - - )} + - - {errors.id && errors.id.message} - {/* 닉네임 입력 */} @@ -292,13 +250,7 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { {errors.name && errors.name.message} -
From 1ddabdab559575ad446e854d6de0660d235690a6 Mon Sep 17 00:00:00 2001 From: suyeonnnnnnn Date: Tue, 14 Nov 2023 12:05:06 +0900 Subject: [PATCH 4/7] Design: Add readnOnly and cursor style to user ID input field --- src/components/Main/UserConfigModal/index.tsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/components/Main/UserConfigModal/index.tsx b/src/components/Main/UserConfigModal/index.tsx index 3977d863..7fbd247f 100644 --- a/src/components/Main/UserConfigModal/index.tsx +++ b/src/components/Main/UserConfigModal/index.tsx @@ -232,6 +232,11 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { placeholder="아이디" value={profile.id} readOnly + sx={{ + cursor: "not-allowed", // 마우스 커서 변경 방지 + _focus: { borderColor: "initial", boxShadow: "none" }, + _hover: { borderColor: "initial" }, + }} width="300px" m="auto" /> From ffa61c14249b229a23ac77b7a93069b9a3fe98cd Mon Sep 17 00:00:00 2001 From: suyeonnnnnnn Date: Tue, 14 Nov 2023 17:05:16 +0900 Subject: [PATCH 5/7] Feat: Add Loading Spinner to UserConfigModal --- src/components/Main/UserConfigModal/index.tsx | 146 ++++++++++-------- 1 file changed, 81 insertions(+), 65 deletions(-) diff --git a/src/components/Main/UserConfigModal/index.tsx b/src/components/Main/UserConfigModal/index.tsx index 7fbd247f..4aacd9e2 100644 --- a/src/components/Main/UserConfigModal/index.tsx +++ b/src/components/Main/UserConfigModal/index.tsx @@ -15,6 +15,7 @@ import { Box, Image, Text, + Spinner, } from "@chakra-ui/react"; import { useRecoilValue } from "recoil"; import { authState } from "../../../recoil/atoms/authState"; @@ -67,6 +68,8 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { message: string; } | null>(null); + const [isLoading, setIsLoading] = useState(false); + const { control, handleSubmit, @@ -83,9 +86,12 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { // 사용자 정보를 폼에 설정 useEffect(() => { + if (isOpen) { + setIsLoading(true); + } if (userInfo && userInfo.auth) { console.log("UserInfo:", userInfo); - // 폼 값 설정 로직 + // 폼 값 설정 로직 setValue("id", userInfo.user.id); setValue("name", userInfo.user.name); setValue("picture", userInfo.user.picture); @@ -94,8 +100,9 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { name: userInfo.user.name, picture: userInfo.user.picture, }); + setIsLoading(false); } - }, [userInfo, setValue, setProfile, isOpen]); + }, [isOpen, userInfo, setValue, setProfile]); // 파일 선택 변경 const handleFileChange = (event: React.ChangeEvent) => { @@ -194,71 +201,80 @@ const UserConfigModal = ({ isOpen, onClose }: UserConfigModalProps) => { {updateStatus.message} )} - {/* 프로필 폼 */} -
- - {selectedFile ? ( - Upload Preview + ) : ( + // 로딩이 완료되면 폼 내용 표시 + + + {selectedFile ? ( + Upload Preview + ) : profile.picture ? ( + Profile Picture + ) : ( + + )} + 이미지 업로드 + - ) : profile.picture ? ( - Profile Picture + {/* 아이디 입력 */} + + - ) : ( - - )} - 이미지 업로드 - - - {/* 아이디 입력 */} - - - - {/* 닉네임 입력 */} - - ( - - )} - /> - - {errors.name && errors.name.message} - - - - + + {/* 닉네임 입력 */} + + ( + + )} + /> + + {errors.name && errors.name.message} + + + + + )} From 7867206be82b2190d9638c0cb9cbe1fd8374c456 Mon Sep 17 00:00:00 2001 From: Yonghun Date: Tue, 14 Nov 2023 17:07:07 +0900 Subject: [PATCH 6/7] Feat: Update fireStore --- src/components/Main/CreateGameModal/index.tsx | 2 +- src/components/common/ToastNotice/index.tsx | 17 ++++++++++++++++- src/pages/Example/index.tsx | 2 +- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/components/Main/CreateGameModal/index.tsx b/src/components/Main/CreateGameModal/index.tsx index fda28609..6dddc39e 100644 --- a/src/components/Main/CreateGameModal/index.tsx +++ b/src/components/Main/CreateGameModal/index.tsx @@ -275,7 +275,7 @@ const CreateGameModal = ({ setModal, socket }: Props) => { // 파이어베이스 게임 데이터 생성 const newData = { ...roomData, - users: [...roomData.users, user.id], + users: [user.id], id: createGame.result.id, host: user.id, createdAt: serverTimestamp(), diff --git a/src/components/common/ToastNotice/index.tsx b/src/components/common/ToastNotice/index.tsx index b9353aa5..7d127709 100644 --- a/src/components/common/ToastNotice/index.tsx +++ b/src/components/common/ToastNotice/index.tsx @@ -2,6 +2,9 @@ import { Button } from "@chakra-ui/react"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; import useFetch from "../../../hooks/useFetch"; +import useFireFetch from "../../../hooks/useFireFetch"; +import { userState } from "../../../recoil/atoms/userState"; +import { useRecoilValue } from "recoil"; const Toast = styled.div` border-radius: 0.5rem; @@ -56,6 +59,11 @@ const ButtonWrap = styled.div` align-items: center; `; +interface Socket { + on(event: string, callback: any): void; + emit(event: string, data: any): void; +} + interface Props { roomData: { id: string; @@ -65,10 +73,14 @@ interface Props { users: string[]; }; setToast: React.Dispatch>; + socket: Socket; } -const ToastNotice: React.FC = ({ roomData, setToast }) => { +const ToastNotice: React.FC = ({ roomData, setToast, socket }) => { const navigate = useNavigate(); + const fireFetch = useFireFetch(); + + const user = useRecoilValue(userState); const join = useFetch({ url: "https://fastcampus-chat.net/chat/participate", @@ -110,6 +122,9 @@ const ToastNotice: React.FC = ({ roomData, setToast }) => { color="#eee" colorScheme="whiteAlpha" onClick={() => { + socket.emit("message-to-server", `${user.id}:${roomData.id}:!#%&(`); + const users = [...roomData.users, user.id]; + fireFetch.updateData("game", roomData.id, { users: users }); join.refresh(); navigate(`/game?gameId=${roomData.id}`); }} diff --git a/src/pages/Example/index.tsx b/src/pages/Example/index.tsx index 21387947..ddff7902 100644 --- a/src/pages/Example/index.tsx +++ b/src/pages/Example/index.tsx @@ -245,7 +245,7 @@ const Example = () => { {modal ? : null} {toast && roomData ? ( - + ) : null} ); From 06bd10294ae7accd872a40f88b0a80ecd9be77c6 Mon Sep 17 00:00:00 2001 From: joanShim Date: Tue, 14 Nov 2023 17:10:20 +0900 Subject: [PATCH 7/7] =?UTF-8?q?Fix:=20=EB=9D=BC=EC=9D=B4=EC=96=B4=20?= =?UTF-8?q?=EC=84=A0=ED=83=9D=20=ED=88=AC=ED=91=9C=20=EB=8D=B0=EC=9D=B4?= =?UTF-8?q?=ED=84=B0=20=EB=B9=84=EB=8F=99=EA=B8=B0=20=EC=9D=B4=EC=8A=88=20?= =?UTF-8?q?=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/Game/GameChat/index.tsx | 1 - src/components/Game/Vote/index.tsx | 65 ++++++++++++++++++-------- 2 files changed, 46 insertions(+), 20 deletions(-) diff --git a/src/components/Game/GameChat/index.tsx b/src/components/Game/GameChat/index.tsx index 21396464..bc61007d 100644 --- a/src/components/Game/GameChat/index.tsx +++ b/src/components/Game/GameChat/index.tsx @@ -29,7 +29,6 @@ interface UserResponse { } const GameChat: React.FC = ({ gameId, gameData }) => { - console.log("GameChat/ gameData:", gameData); const token = JSON.parse(localStorage.getItem("token") as string); const socket = io(`https://fastcampus-chat.net/chat?chatId=${gameId}`, { diff --git a/src/components/Game/Vote/index.tsx b/src/components/Game/Vote/index.tsx index b2dde57c..e15c8cc8 100644 --- a/src/components/Game/Vote/index.tsx +++ b/src/components/Game/Vote/index.tsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useEffect, useState } from "react"; import { Modal, ModalOverlay, @@ -12,8 +12,9 @@ import { RadioGroup, Stack, } from "@chakra-ui/react"; -import useFireFetch from "../../../hooks/useFireFetch"; -import { arrayUnion } from "firebase/firestore"; +// import useFireFetch from "../../../hooks/useFireFetch"; +import { db } from "../../../firebase/firebase"; +import { arrayUnion, updateDoc, doc, getDoc } from "firebase/firestore"; import calculateVote from "./CalculateVote"; import { useRecoilValue } from "recoil"; import { userState } from "../../../recoil/atoms/userState"; @@ -35,9 +36,26 @@ const Vote: React.FC = ({ gameData, }): React.ReactElement => { const [selectedUser, setSelectedUser] = useState(""); - const fireFetch = useFireFetch(); - const fetchData = fireFetch.useGetSome("game", "id", gameData.id) - .data[0] as GameData; + const [fetchData, setFetchData] = useState(null); + // const fireFetch = useFireFetch(); + useEffect(() => { + const fetchDataFromFirebase = async () => { + try { + const docRef = doc(db, "game", gameData.id); + const docSnap = await getDoc(docRef); + + if (docSnap.exists()) { + const updatedData = docSnap.data() as GameData; + console.log("updatedData :", updatedData); + setFetchData(updatedData); + } + } catch (error) { + console.error("Error fetching data:", error); + } + }; + + fetchDataFromFirebase(); + }, []); const user = useRecoilValue(userState); @@ -45,18 +63,26 @@ const Vote: React.FC = ({ setSelectedUser(value); }; - const handleVoteSubmit = () => { + const handleVoteSubmit = async () => { if (selectedUser !== "") { - fireFetch.updateData("game", gameData.id, { - votedFor: arrayUnion({ by: user.id, liar: selectedUser }), - }); + try { + const docRef = doc(db, "game", gameData.id); + await updateDoc(docRef, { + votedFor: arrayUnion({ by: user.id, liar: selectedUser }), + }); + + const updatedDocSnap = await getDoc(docRef); + const updatedData = updatedDocSnap.data() as GameData; - console.log("fetchData", fetchData); - const voteResult = calculateVote(fetchData); + console.log("submit/ Updated Data:", updatedData); - console.log("Vote result: " + voteResult); + const voteResult = calculateVote(updatedData); + console.log("Vote result: " + voteResult); - onClose(selectedUser); + onClose(selectedUser); + } catch (error) { + console.error("Error updating data:", error); + } } }; @@ -70,11 +96,12 @@ const Vote: React.FC = ({ - {gameData.users.map((user) => ( - - {user} - - ))} + {fetchData && + fetchData.users.map((user) => ( + + {user} + + ))}