Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/update api #45

Merged
merged 2 commits into from
Oct 31, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import React, { useRef, useState, useEffect, useCallback } from "react";
import { useRouter, useParams } from "next/navigation";
import { v4 as uuidv4 } from "uuid";
import { useUserDataStore } from "../stores/useUserDataStore"; // zustand store import

export default function PasswordInput() {
const [password, setPassword] = useState(["", "", "", ""]);
Expand All @@ -11,8 +12,8 @@ export default function PasswordInput() {
const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
const router = useRouter();
const { id, nonMemberId } = useParams();
const setUserData = useUserDataStore((state) => state.setUserData); // Use zustand's setUserData

// Define submitPassword before useEffect
const submitPassword = useCallback(async () => {
const fullPassword = password.join("");

Expand All @@ -38,6 +39,16 @@ export default function PasswordInput() {
);

if (response.ok) {
const data = await response.json(); // Get the JSON response

// Save data in zustand store
setUserData({
nonMemberId: data.nonMemberId,
name: data.name,
bookmarkUrls: data.bookmarkUrls || [],
storeUrls: data.storeUrls || [],
});

router.push(`/event-maps/${id}/${nonMemberId}/load-mappin-edit`);
} else {
setHasError(true);
Expand All @@ -47,7 +58,7 @@ export default function PasswordInput() {
} catch (error) {
setHasError(true);
}
}, [id, nonMemberId, password, router]);
}, [id, nonMemberId, password, router, setUserData]);

useEffect(() => {
if (password.every((digit) => digit !== "")) {
Expand Down Expand Up @@ -98,7 +109,7 @@ export default function PasswordInput() {
<div className="inline-flex items-center justify-start gap-4 mb-4">
{password.map((_, i) => (
<div
key={uuidv4()} // Unique key for each render
key={uuidv4()}
className={`w-14 h-14 p-4 bg-[#f7f7f7] rounded-lg inline-flex items-center ${
hasError ? "border-2 border-primary-50" : ""
} ${currentIndex === i ? "border-2 border-gray-950" : ""}`}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,73 @@
"use client";

import React, { useState, useEffect, FormEvent } from "react";
import { useRouter, useParams } from "next/navigation";
import LinkField from "./LinkField";
import { useUserDataStore } from "../../stores/useUserDataStore";

interface FormProps {
userName: string;
}

export default function Form({ userName }: FormProps) {
const [mapLinks, setMapLinks] = useState([""]);
const [storeLinks, setStoreLinks] = useState([""]);
export default function Form() {
const { userData } = useUserDataStore(); // Access userData from zustand
const [mapLinks, setMapLinks] = useState<string[]>([]);
const [storeLinks, setStoreLinks] = useState<string[]>([]);
const [isTooltipVisible, setIsTooltipVisible] = useState(true);
const [isFormComplete, setIsFormComplete] = useState(false); // isFormComplete 추가
const [isFormComplete, setIsFormComplete] = useState(false);
const router = useRouter();
const { id } = useParams(); // Retrieve `id` from the route parameters

// Load mapLinks and storeLinks from the store when the component mounts
useEffect(() => {
if (userData) {
setMapLinks(
userData.bookmarkUrls?.filter((link) => link.trim() !== "") || []
);
setStoreLinks(
userData.storeUrls?.filter((link) => link.trim() !== "") || []
);
}
}, [userData]);

// mapLinks와 storeLinks가 모두 입력되었을 때만 isFormComplete를 true로 설정
// Check if form is complete whenever mapLinks or storeLinks change
useEffect(() => {
setIsFormComplete(
mapLinks.some((link) => link.trim() !== "") &&
storeLinks.some((link) => link.trim() !== "")
mapLinks.length > 0 && storeLinks.length > 0 // Check for non-empty lists
);
}, [mapLinks, storeLinks]);

const handleSubmit = (e: FormEvent) => {
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();

// Filter out any empty strings just before submitting
const filteredMapLinks = mapLinks.filter((link) => link.trim() !== "");
const filteredStoreLinks = storeLinks.filter((link) => link.trim() !== "");

const formData = {
userName,
mapLinks,
storeLinks,
nonMemberId: userData?.nonMemberId, // Assuming nonMemberId is available in userData
bookmarkUrls: filteredMapLinks,
storeUrls: filteredStoreLinks,
};
console.log("폼 데이터:", formData);

try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_BASE_URL}/nonmembers/pings`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(formData),
}
);

if (response.ok) {
console.log("데이터가 성공적으로 전송되었습니다.");
router.push(`/event-maps/${id}`); // Redirect to the specified route on success
} else {
console.error("데이터 전송 실패:", response.status);
}
} catch (error) {
console.error("서버 오류 발생:", error);
}
};

return (
Expand All @@ -38,7 +77,9 @@ export default function Form({ userName }: FormProps) {
label="맵핀 모음 링크"
placeholder="링크 붙여넣기"
value={mapLinks}
onChange={setMapLinks}
onChange={(links) =>
setMapLinks(links.filter((link) => link.trim() !== ""))
}
showTooltip={isTooltipVisible}
onInfoClick={() => setIsTooltipVisible(true)}
/>
Expand All @@ -47,7 +88,9 @@ export default function Form({ userName }: FormProps) {
label="가게 정보 링크"
placeholder="링크 붙여넣기"
value={storeLinks}
onChange={setStoreLinks}
onChange={(links) =>
setStoreLinks(links.filter((link) => link.trim() !== ""))
}
/>

<button
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import { nanoid } from "nanoid";
import Image from "next/image";
import { useUserDataStore } from "../../stores/useUserDataStore";

interface LinkFieldProps {
label: string; // label 속성 추가
label: string;
placeholder: string;
value: string[];
onChange: (value: string[]) => void;
Expand All @@ -19,10 +20,18 @@ export default function LinkField({
showTooltip = true,
onInfoClick,
}: LinkFieldProps) {
const userData = useUserDataStore((state) => state.userData); // Use zustand's userData
const [inputFields, setInputFields] = useState(
value.map((val) => ({ id: nanoid(), text: val }))
);

useEffect(() => {
// Update input fields with data from zustand if available
const initialData =
label === "맵핀 모음 링크" ? userData.bookmarkUrls : userData.storeUrls;
setInputFields(initialData.map((val) => ({ id: nanoid(), text: val })));
}, [label, userData]);

const handleInputChange = (id: string, inputValue: string) => {
const newInputs = inputFields.map((field) =>
field.id === id ? { ...field, text: inputValue } : field
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import Image from "next/image";
import { useRouter, useParams } from "next/navigation";
import ExitModal from "@/app/event-maps/[id]/[nonMemberId]/components/PinExitModal";
import Form from "./components/Form";
import { useUserDataStore } from "../stores/useUserDataStore";

export default function Page() {
const [userName] = useState("규리");
const userName = useUserDataStore((state) => state.userData.name); // Get userName from zustand
const [isModalOpen, setIsModalOpen] = useState(false);
const router = useRouter();
const { id } = useParams();
Expand Down Expand Up @@ -46,7 +47,7 @@ export default function Page() {
{userName}님의 맵핀 모음이에요
</div>
)}
<Form userName={userName} />
<Form />
<div className="h-[20px]" />

{isModalOpen && (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { create } from "zustand";

interface UserData {
nonMemberId: number | null;
name: string;
bookmarkUrls: string[];
storeUrls: string[];
}

interface UserDataStore {
userData: UserData;
setUserData: (data: UserData) => void;
}

export const useUserDataStore = create<UserDataStore>((set) => ({
userData: {
nonMemberId: null,
name: "",
bookmarkUrls: [],
storeUrls: [],
},
setUserData: (data) => set({ userData: data }),
}));
1 change: 0 additions & 1 deletion fe/src/app/event-maps/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ export default function Page() {
const result = await response.json();
setData(result);
console.log("API Response Data:", JSON.stringify(result, null, 2));

if (result.px && result.py) {
console.log("Moving to location:", result.py, result.px);
moveToLocation(result.py, result.px);
Expand Down
Loading