AnswerSurvey.tsx 4.08 KB
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
1
import React, { FormEvent, useEffect, useState } from "react";
Yoon, Daeki's avatar
Yoon, Daeki committed
2
import { useParams } 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
15
16
17
18
19
  const [error, setError] = useState("");

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

Yoon, Daeki's avatar
Yoon, Daeki committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    console.log("answers:", answers);
    const needAnswer = answers.some((answer) => !answer.requiredCheck);
    if (needAnswer) {
      alert("필수질문에 응답하셔야 합니다.");
      return;
    }
    if (!survey) {
      return;
    }
    try {
      const fileAnswers = answers.filter(
        (answer) => answer.question.type === "file"
      );
      const otherAnswers = answers.filter(
        (answer) => answer.question.type !== "file"
      );

      console.log("file answers:", fileAnswers);
      console.log("other answers:", otherAnswers);

      const forms = fileAnswers.map((answer) => {
        const formData = new FormData();
        formData.append("surveyId", survey._id!);
        formData.append("questionId", answer.question._id!);
        formData.append("guestId", "guest");

        const files: FileList = answer.content;
        [...files].map((f) => {
          formData.append("uploadFiles", f);
        });
        return formData;
      });

      setError("");
      const results = await answerApi.save(
        otherAnswers.map((answer) => ({
          questionId: answer.question._id!,
          surveyId: survey._id!,
          questId: "guest",
          content: answer.content,
        }))
      );
      console.log("results:", results);

      const result = await Promise.all(
        forms.map(async (form) => await answerApi.saveForm(form))
      );

      console.log("result:", result);

      // const newAnswer: IAnswer = await answerApi.saveAnswers(formData);
      // console.log(newAnswer);
      // sessionStorage.setItem(`survey_${surveyId}`, surveyId ?? "");
      // navigate("/survey/complete", { replace: false });
    } catch (error) {
      catchErrors(error, setError);
    } finally {
      // setLoading(false);
    }
  };
Yoon, Daeki's avatar
Yoon, Daeki committed
82
83
84
85

  async function getSurvey(surveyId: string) {
    try {
      setError("");
Yoon, Daeki's avatar
Yoon, Daeki committed
86
      const survey: ISurvey = await surveyApi.getSurveyById(surveyId);
Yoon, Daeki's avatar
Yoon, Daeki committed
87
      console.log("survey가져옴ㅎㅎ", survey);
Yoon, Daeki's avatar
Yoon, Daeki committed
88
89
90
91
92
93
94
95
      const answers = survey.questions.map((question) => {
        return {
          surveyId: survey._id!,
          question: question,
          requiredCheck: false,
          content: null,
        };
      });
Yoon, Daeki's avatar
Yoon, Daeki committed
96
      setSurvey(survey);
Yoon, Daeki's avatar
Yoon, Daeki committed
97
      setAnswers(answers);
Yoon, Daeki's avatar
Yoon, Daeki committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
      // 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">
          <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>
Yoon, Daeki's avatar
Yoon, Daeki committed
120
          {answers.map((answer) => {
Yoon, Daeki's avatar
Yoon, Daeki committed
121
122
            return (
              <AQuestion
Yoon, Daeki's avatar
Yoon, Daeki committed
123
124
125
126
                key={answer.question._id}
                question={answer.question}
                answer={answer}
              />
Yoon, Daeki's avatar
Yoon, Daeki committed
127
            );
Yoon, Daeki's avatar
Yoon, Daeki committed
128
          })}
Yoon, Daeki's avatar
Yoon, Daeki committed
129
130
131
132
133
134
135
136
137
138
139
140
141
          <div>
            <button
              type="submit"
              className="rounded bg-themeColor my-5 py-2 px-5 font-bold text-white"
            >
              제출하기
            </button>
          </div>
        </div>
      </div>
    </form>
  );
};