AnswerSurveyForm.tsx 4.13 KB
Newer Older
1
import React, { FormEvent, useEffect, useRef, useState } from "react";
jang dong hyeok's avatar
jang dong hyeok committed
2
import { useNavigate, useParams } from "react-router-dom";
3
import { surveyApi, answerApi } from "../apis";
Lee SeoYeon's avatar
Lee SeoYeon committed
4
import { catchErrors } from "../helpers";
Yoon, Daeki's avatar
Yoon, Daeki committed
5
import { AnswerSurveyType, AnswerType, SurveyType } from "../types";
Lee SeoYeon's avatar
Lee SeoYeon committed
6
import { AQuestion } from "./AQuestion";
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
7

8
export const AnswerSurveyForm = () => {
Lee SeoYeon's avatar
Lee SeoYeon committed
9
  let { surveyId } = useParams<{ surveyId: string }>();
10
  const [files, setFiles] = useState<{ questionId: string; file: File }[]>([]);
Lee SeoYeon's avatar
Lee SeoYeon committed
11
12
13
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
14
  const navigate = useNavigate();
Lee SeoYeon's avatar
Lee SeoYeon committed
15
  const [survey, setSurvey] = useState<SurveyType>({
Yoon, Daeki's avatar
Yoon, Daeki committed
16
    _id: surveyId || "",
Lee SeoYeon's avatar
Lee SeoYeon committed
17
18
19
20
21
    user: {},
    title: "",
    comment: "",
    questions: [],
  });
22

Yoon, Daeki's avatar
Yoon, Daeki committed
23
  const answerSurvey = useRef<AnswerSurveyType>({
Jiwon Yoon's avatar
Jiwon Yoon committed
24
25
26
27
28
    _id: "surveyId",
    user: {},
    title: "",
    comment: "",
    questions: [],
Jiwon Yoon's avatar
Jiwon Yoon committed
29
  });
Lee SeoYeon's avatar
Lee SeoYeon committed
30

Jiwon Yoon's avatar
Jiwon Yoon committed
31
32
33
  useEffect(() => {
    ansSurvey();
  }, [surveyId]);
Yoon, Daeki's avatar
Yoon, Daeki committed
34

35
  const isSurvey = localStorage.getItem(`survey_${surveyId}`);
Yoon, Daeki's avatar
Yoon, Daeki committed
36

37
38
  if (isSurvey) {
    console.log("object", isSurvey);
Lee SeoYeon's avatar
Lee SeoYeon committed
39
    navigate("/survey/same");
40
  }
Jiwon Yoon's avatar
Jiwon Yoon committed
41

42
43
44
45
46
  const addFiles = (oneFile: { questionId: string; file: File }) => {
    if (!files.find((a) => a.questionId === oneFile.questionId)) {
      setFiles([...files, oneFile]);
    }
  };
Yoon, Daeki's avatar
Yoon, Daeki committed
47

Lee SeoYeon's avatar
Lee SeoYeon committed
48
49
50
  async function ansSurvey() {
    try {
      if (surveyId) {
Jiwon Yoon's avatar
Jiwon Yoon committed
51
52
53
54
55
56
        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);
57
58
59
          setSuccess(true);
          setError("");
        }
Lee SeoYeon's avatar
Lee SeoYeon committed
60
61
62
63
64
65
66
67
68
69
      } else {
        setLoading(true);
      }
    } catch (error) {
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

70
  async function handleSubmit(event: FormEvent) {
Jiwon Yoon's avatar
Jiwon Yoon committed
71
    event.preventDefault();
Jiwon Yoon's avatar
Jiwon Yoon committed
72
    const answers = answerSurvey.current.questions.map((q: any) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
73
      return { questionId: q._id, answer: q.answer, type: q.type };
Jiwon Yoon's avatar
Jiwon Yoon committed
74
75
76
77
78
79
80
81
82
83
    });
    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);
Jiwon Yoon's avatar
Jiwon Yoon committed
84
        formData.append("guestId", "guest1");
Jiwon Yoon's avatar
Jiwon Yoon committed
85
86
87
88
89
        formData.append("answers", JSON.stringify(answers));
        files.map((f) => {
          formData.append("uploadFiles", f.file);
        });
        const newAnswer: AnswerType = await answerApi.saveAnswers(formData);
Jiwon Yoon's avatar
Jiwon Yoon committed
90
        console.log(newAnswer);
91
        localStorage.setItem(`survey_${surveyId}`, surveyId ?? "");
Lee SeoYeon's avatar
Lee SeoYeon committed
92
        navigate("/survey/complete");
93

Jiwon Yoon's avatar
Jiwon Yoon committed
94
95
96
97
98
99
100
        setSuccess(true);
        setError("");
      } catch (error) {
        catchErrors(error, setError);
      } finally {
        setLoading(false);
      }
101
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
102
103
  }

Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
104
  return (
Jiwon Yoon's avatar
Jiwon Yoon committed
105
    <>
Jiwon Yoon's avatar
Jiwon Yoon committed
106
      {console.log("rendering survey form", answerSurvey.current)}
Jiwon Yoon's avatar
Jiwon Yoon committed
107
108
109
110
111
112
113
      <form onSubmit={handleSubmit}>
        <div className="flex flex-col place-items-center">
          <div className="flex flex-col container place-items-center mt-4">
            <p className="font-bold text-4xl text-center m-2">{survey.title}</p>
            <p className="font-bold text-1xl text-center m-2">
              {survey.comment}
            </p>
Jiwon Yoon's avatar
Jiwon Yoon committed
114
            {survey.questions.map((question, index) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
115
116
              return (
                <AQuestion
Yoon, Daeki's avatar
Yoon, Daeki committed
117
                  key={question._id}
Jiwon Yoon's avatar
Jiwon Yoon committed
118
                  question={question}
Jiwon Yoon's avatar
Jiwon Yoon committed
119
                  answerQuestion={answerSurvey.current.questions[index]}
120
                  addFiles={addFiles}
Jiwon Yoon's avatar
Jiwon Yoon committed
121
122
123
124
125
126
127
128
129
130
131
132
                ></AQuestion>
              );
            })}
            <div>
              <button
                type="submit"
                className="rounded bg-themeColor my-5 py-2 px-5 font-bold text-white"
              >
                제출하기
              </button>
            </div>
          </div>
Lee SeoYeon's avatar
Lee SeoYeon committed
133
        </div>
Jiwon Yoon's avatar
Jiwon Yoon committed
134
135
      </form>
    </>
Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
136
137
  );
};