SurveyForm.tsx 3.87 KB
Newer Older
1
import React, { FormEvent, useEffect, useRef, useState } from "react";
Lee SeoYeon's avatar
Lee SeoYeon committed
2
import { useParams } from "react-router-dom";
3
import { surveyApi, answerApi } from "../apis";
Lee SeoYeon's avatar
Lee SeoYeon committed
4
import { catchErrors } from "../helpers";
Jiwon Yoon's avatar
Jiwon Yoon committed
5
import { Question } from "../questions";
Jiwon Yoon's avatar
Jiwon Yoon committed
6
import { AnswerType, SurveyType } from "../types";
Lee SeoYeon's avatar
Lee SeoYeon committed
7
import { AQuestion } from "./AQuestion";
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
8

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

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

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

36
37
38
39
40
  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
41

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

64
  async function handleSubmit(event: FormEvent) {
Jiwon Yoon's avatar
Jiwon Yoon committed
65
    event.preventDefault();
Jiwon Yoon's avatar
Jiwon Yoon committed
66
67
68
69
70
71
72
73
74
75
76
77
    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);
Jiwon Yoon's avatar
Jiwon Yoon committed
78
        formData.append("guestId", "quest1");
Jiwon Yoon's avatar
Jiwon Yoon committed
79
80
81
82
83
        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
84
        console.log(newAnswer);
Jiwon Yoon's avatar
Jiwon Yoon committed
85
86
87
88
89
90
91
        setSuccess(true);
        setError("");
      } catch (error) {
        catchErrors(error, setError);
      } finally {
        setLoading(false);
      }
92
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
93
94
  }

Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
95
  return (
Jiwon Yoon's avatar
Jiwon Yoon committed
96
    <>
Jiwon Yoon's avatar
Jiwon Yoon committed
97
      {console.log("rendering survey form", answerSurvey.current)}
Jiwon Yoon's avatar
Jiwon Yoon committed
98
99
100
101
102
103
104
      <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
105
            {survey.questions.map((question, index) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
106
107
108
              return (
                <AQuestion
                  question={question}
Jiwon Yoon's avatar
Jiwon Yoon committed
109
                  answerQuestion={answerSurvey.current.questions[index]}
110
                  addFiles={addFiles}
Jiwon Yoon's avatar
Jiwon Yoon committed
111
112
113
114
115
116
117
118
119
120
121
122
                ></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
123
        </div>
Jiwon Yoon's avatar
Jiwon Yoon committed
124
125
      </form>
    </>
Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
126
127
  );
};