AnswerSurvey.tsx 4.28 KB
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
1
import React, { FormEvent, useEffect, useState } from "react";
2
import { useParams, useNavigate } from "react-router-dom";
Yoon, Daeki's avatar
Yoon, Daeki committed
3
import { answerApi, surveyApi } from "../apis";
Yoon, Daeki's avatar
Yoon, Daeki committed
4
5
import { catchErrors } from "../helpers";
import { SpinnerIcon } from "../icons";
Yoon, Daeki's avatar
Yoon, Daeki committed
6
7
import { IAnswer, ISurvey } from "../types";
import { AQuestion } from "./AQuestion";
Yoon, Daeki's avatar
Yoon, Daeki committed
8
9
10
11
12

export const AnswerSurvey = () => {
  let { surveyId } = useParams<{ surveyId: string }>();

  const [survey, setSurvey] = useState<ISurvey>();
Yoon, Daeki's avatar
Yoon, Daeki committed
13
  const [answers, setAnswers] = useState<IAnswer[]>([]);
Yoon, Daeki's avatar
Yoon, Daeki committed
14
  const [error, setError] = useState("");
15
  const navigate = useNavigate();
Yoon, Daeki's avatar
Yoon, Daeki committed
16
17
18
19
20

  useEffect(() => {
    surveyId && getSurvey(surveyId);
  }, [surveyId]);

Yoon, Daeki's avatar
Yoon, Daeki committed
21
22
23
  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    console.log("answers:", answers);
Jiwon Yoon's avatar
Jiwon Yoon committed
24
25
26
    const needAnswer = answers.some(
      (answer) => answer.question.isRequired && !answer.requiredCheck
    );
Yoon, Daeki's avatar
Yoon, Daeki committed
27
28
29
30
31
32
33
    if (needAnswer) {
      alert("필수질문에 응답하셔야 합니다.");
      return;
    }
    if (!survey) {
      return;
    }
34
35
36
37
38
39
40
41
    if (confirm("제출하시겠습니까?")) {
      try {
        const fileAnswers = answers.filter(
          (answer) => answer.question.type === "file"
        );
        const otherAnswers = answers.filter(
          (answer) => answer.question.type !== "file"
        );
Yoon, Daeki's avatar
Yoon, Daeki committed
42

43
44
        console.log("file answers:", fileAnswers);
        console.log("other answers:", otherAnswers);
Yoon, Daeki's avatar
Yoon, Daeki committed
45

46
47
48
49
50
        const forms = fileAnswers.map((answer) => {
          const formData = new FormData();
          formData.append("surveyId", survey._id!);
          formData.append("questionId", answer.question._id!);
          formData.append("guestId", "guest");
Yoon, Daeki's avatar
Yoon, Daeki committed
51

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
          const files: FileList = answer.content;
          files &&
            [...files].map((f) => {
              console.log("파일 없음", f);
              formData.append("uploadFiles", f);
            });
          return formData;
        });
        console.log("forms", forms);
        setError("");
        const results = await answerApi.save(
          otherAnswers.map((answer) => ({
            questionId: answer.question._id!,
            surveyId: survey._id!,
            guestId: "guest",
            content: answer.content,
          }))
        );
        console.log("results:", results);
Yoon, Daeki's avatar
Yoon, Daeki committed
71

72
73
74
        const result = await Promise.all(
          forms.map(async (form) => await answerApi.saveForm(form))
        );
Yoon, Daeki's avatar
Yoon, Daeki committed
75

76
77
78
79
80
81
82
83
84
        console.log("result:", result);
        navigate("/");
      } catch (error) {
        catchErrors(error, setError);
      } finally {
        // setLoading(false);
      }
    } else {
      return;
Yoon, Daeki's avatar
Yoon, Daeki committed
85
86
    }
  };
Yoon, Daeki's avatar
Yoon, Daeki committed
87
88
89
90

  async function getSurvey(surveyId: string) {
    try {
      setError("");
Yoon, Daeki's avatar
Yoon, Daeki committed
91
      const survey: ISurvey = await surveyApi.getSurveyById(surveyId);
Yoon, Daeki's avatar
Yoon, Daeki committed
92
      console.log("survey가져옴ㅎㅎ", survey);
Yoon, Daeki's avatar
Yoon, Daeki committed
93
94
95
96
97
98
99
100
      const answers = survey.questions.map((question) => {
        return {
          surveyId: survey._id!,
          question: question,
          requiredCheck: false,
          content: null,
        };
      });
Yoon, Daeki's avatar
Yoon, Daeki committed
101
      setSurvey(survey);
Yoon, Daeki's avatar
Yoon, Daeki committed
102
      setAnswers(answers);
Yoon, Daeki's avatar
Yoon, Daeki committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
      // setSuccess(true);
    } catch (error) {
      catchErrors(error, setError);
    } finally {
      // setLoading(false);
    }
  }

  if (!survey) {
    return (
      <div className="flex justify-center mt-5">
        <SpinnerIcon className="animate-spin h-10 w-10 mr-1 bg-white text-slate-500" />
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit}>
      <div className="flex flex-col place-items-center">
        <div className="flex flex-col container place-items-center mt-4">
Jiwon Yoon's avatar
Jiwon Yoon committed
123
124
125
126
127
128
          <p className="font-bold md:text-4xl text-2xl text-center m-2">
            {survey.title}
          </p>
          <p className="font-bold md:text-1xl text-center m-2">
            {survey.comment}
          </p>
Yoon, Daeki's avatar
Yoon, Daeki committed
129
          {answers.map((answer) => {
Yoon, Daeki's avatar
Yoon, Daeki committed
130
131
            return (
              <AQuestion
Yoon, Daeki's avatar
Yoon, Daeki committed
132
133
134
135
                key={answer.question._id}
                question={answer.question}
                answer={answer}
              />
Yoon, Daeki's avatar
Yoon, Daeki committed
136
            );
Yoon, Daeki's avatar
Yoon, Daeki committed
137
          })}
Yoon, Daeki's avatar
Yoon, Daeki committed
138
139
140
141
142
143
144
145
146
147
148
149
150
          <div>
            <button
              type="submit"
              className="rounded bg-themeColor my-5 py-2 px-5 font-bold text-white"
            >
              제출하기
            </button>
          </div>
        </div>
      </div>
    </form>
  );
};