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 { AnswerType, SurveyType } from "../types"; import { AQuestion } from "./AQuestion"; export const SurveyForm = () => { let { surveyId } = useParams<{ surveyId: string }>(); const [files, setFiles] = useState<{ questionId: string; file: File }[]>([]); 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 answer = useRef({ surveyId: "surveyId", guestId: "", answers: [], }); 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 answersurvey: any = await surveyApi.ansSurvey(surveyId); console.log(answersurvey); const questionIds = answersurvey.questions.map((el: any) => { return { questionId: el._id, type: el.type, answer: "" }; }); console.log(questionIds); if (answersurvey) { // setResponse({ // ...answer, // surveyId: answersurvey._id, // answers: questionIds, // }); answer.current.surveyId = answersurvey._id; answer.current.guestId = answersurvey.guestId; answer.current.answers = questionIds; setSurvey(answersurvey); setSuccess(true); setError(""); } } else { setLoading(true); } } catch (error) { catchErrors(error, setError); } finally { setLoading(false); } } useEffect(() => { ansSurvey(); }, [surveyId]); async function handleSubmit(event: FormEvent) { event.preventDefault(); try { const formData = new FormData(); formData.append("surveyId", answer.current.surveyId); formData.append("guestId", ""); formData.append("answers", JSON.stringify(answer.current.answers)); files.map((f) => { formData.append("files", f.file); }); const newAnswer: AnswerType = await answerApi.saveAnswers(formData); localStorage.setItem(`survey_${surveyId}`, surveyId ?? ""); alert("제출되었습니다"); navigate(`/`); // console.log(newAnswer); setSuccess(true); setError(""); } catch (error) { catchErrors(error, setError); } finally { setLoading(false); } } const handleAnswer = () => { console.log("handle answer:", answer.current); // const newList = [...answer.answers]; // setResponse({ ...answer, answers: newList }); }; return ( <> {console.log("rendering survey form", answer.current)}

{survey.title}

{survey.comment}

{survey.questions.map((question) => { return ( ans.questionId === question._id )} addFiles={addFiles} handleAnswer={handleAnswer} > ); })}
); };