AnswerSurveyForm.tsx 4.26 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 }[]>([]);
Jiwon Yoon's avatar
Jiwon Yoon committed
11
  const [requiredErrorMessage, setRequiredErrorMessage] = useState("");
Lee SeoYeon's avatar
Lee SeoYeon committed
12
13
14
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
15
  const navigate = useNavigate();
Lee SeoYeon's avatar
Lee SeoYeon committed
16
  const [survey, setSurvey] = useState<SurveyType>({
Yoon, Daeki's avatar
Yoon, Daeki committed
17
    _id: surveyId || "",
Lee SeoYeon's avatar
Lee SeoYeon committed
18
19
20
21
22
    user: {},
    title: "",
    comment: "",
    questions: [],
  });
23

Yoon, Daeki's avatar
Yoon, Daeki committed
24
  const answerSurvey = useRef<AnswerSurveyType>({
Jiwon Yoon's avatar
Jiwon Yoon committed
25
26
27
28
29
    _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
  useEffect(() => {
    ansSurvey();
  }, [surveyId]);
Yoon, Daeki's avatar
Yoon, Daeki committed
35

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

Jiwon Yoon's avatar
Jiwon Yoon committed
38
39
40
41
42
  // if (isSurvey) {
  //   console.log("object", isSurvey);
  //   alert("제출한 설문조사입니다");
  //   navigate("/");
  // }
Jiwon Yoon's avatar
Jiwon Yoon committed
43

44
45
46
47
48
  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
49

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

72
  async function handleSubmit(event: FormEvent) {
Jiwon Yoon's avatar
Jiwon Yoon committed
73
    event.preventDefault();
Jiwon Yoon's avatar
Jiwon Yoon committed
74
    const answers = answerSurvey.current.questions.map((q: any) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
75
      return { questionId: q._id, answer: q.answer, type: q.type };
Jiwon Yoon's avatar
Jiwon Yoon committed
76
77
78
79
80
81
82
83
84
85
    });
    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
86
        formData.append("guestId", "guest1");
Jiwon Yoon's avatar
Jiwon Yoon committed
87
88
89
90
91
        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
92
        console.log(newAnswer);
93
        localStorage.setItem(`survey_${surveyId}`, surveyId ?? "");
Jiwon Yoon's avatar
Jiwon Yoon committed
94
        // alert("제출되었습니다");
95

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

Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
106
  return (
Jiwon Yoon's avatar
Jiwon Yoon committed
107
    <>
Jiwon Yoon's avatar
Jiwon Yoon committed
108
      {console.log("rendering survey form", answerSurvey.current)}
Jiwon Yoon's avatar
Jiwon Yoon committed
109
110
111
112
113
114
115
      <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
116
            {survey.questions.map((question, index) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
117
118
              return (
                <AQuestion
Yoon, Daeki's avatar
Yoon, Daeki committed
119
                  key={question._id}
Jiwon Yoon's avatar
Jiwon Yoon committed
120
                  question={question}
Jiwon Yoon's avatar
Jiwon Yoon committed
121
                  answerQuestion={answerSurvey.current.questions[index]}
122
                  addFiles={addFiles}
Jiwon Yoon's avatar
Jiwon Yoon committed
123
124
125
126
127
128
129
130
131
132
133
134
                ></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
135
        </div>
Jiwon Yoon's avatar
Jiwon Yoon committed
136
137
      </form>
    </>
Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
138
139
  );
};