import React, { FormEvent, useEffect, useRef, useState } from "react"; import { Link, useNavigate } from "react-router-dom"; import { useParams } from "react-router-dom"; import { surveyApi, answerApi } from "../apis"; import { catchErrors } from "../helpers"; import { Question } from "../questions"; import { AnswerType, SurveyType } from "../types"; import { AQuestion } from "./AQuestion"; export const AnswerSurveyForm = () => { let { surveyId } = useParams<{ surveyId: string }>(); const [files, setFiles] = useState<{ questionId: string; file: File }[]>([]); const [requiredErrorMessage, setRequiredErrorMessage] = useState(""); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const [success, setSuccess] = useState(false); const navigate = useNavigate(); const [survey, setSurvey] = useState({ _id: surveyId, user: {}, title: "", comment: "", questions: [], }); const answerSurvey = useRef({ _id: "surveyId", user: {}, title: "", comment: "", questions: [], }); useEffect(() => { ansSurvey(); }, [surveyId]); const isSurvey = localStorage.getItem(`survey_${surveyId}`); if (isSurvey) { console.log("object", isSurvey); alert("제출한 설문조사입니다"); navigate("/"); } const addFiles = (oneFile: { questionId: string; file: File }) => { if (!files.find((a) => a.questionId === oneFile.questionId)) { setFiles([...files, oneFile]); } }; async function ansSurvey() { try { if (surveyId) { const getSurvey: any = await surveyApi.ansSurvey(surveyId); console.log("survey가져옴ㅎㅎ", getSurvey); if (getSurvey) { answerSurvey.current._id = getSurvey._id; answerSurvey.current.questions = getSurvey.questions; setSurvey(getSurvey); setSuccess(true); setError(""); } } else { setLoading(true); } } catch (error) { catchErrors(error, setError); } finally { setLoading(false); } } async function handleSubmit(event: FormEvent) { event.preventDefault(); const answers = answerSurvey.current.questions.map((q: any) => { return { questionId: q.questionId, answer: q.answer, type: q.type }; }); const requiredErrorQ = answerSurvey.current.questions.find( (q: any) => q.isRequired && q.isRequired !== q.requiredCheck ); if (requiredErrorQ) { alert("필수질문에 응답하지 않으셨습니다."); } else { try { const formData = new FormData(); formData.append("surveyId", answerSurvey.current._id); formData.append("guestId", "quest1"); formData.append("answers", JSON.stringify(answers)); files.map((f) => { formData.append("uploadFiles", f.file); }); const newAnswer: AnswerType = await answerApi.saveAnswers(formData); console.log(newAnswer); localStorage.setItem(`survey_${surveyId}`, surveyId ?? ""); alert("제출되었습니다"); setSuccess(true); setError(""); } catch (error) { catchErrors(error, setError); } finally { setLoading(false); } } } return ( <> {console.log("rendering survey form", answerSurvey.current)}

{survey.title}

{survey.comment}

{survey.questions.map((question, index) => { return ( ); })}
); };