SurveyForm.tsx 3.95 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 { AnswerType, SurveyType } from "../types";
Lee SeoYeon's avatar
Lee SeoYeon committed
6
import { AQuestion } from "./AQuestion";
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
7

Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
8
export const SurveyForm = () => {
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
14
15
16
17
18
19
20
  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: [],
  });
21
22

  const answer = useRef<AnswerType>({
23
    surveyId: "surveyId",
Jiwon Yoon's avatar
Jiwon Yoon committed
24
    guestId: "",
Yoon, Daeki's avatar
Yoon, Daeki committed
25
    answers: [],
Jiwon Yoon's avatar
Jiwon Yoon committed
26
  });
Lee SeoYeon's avatar
Lee SeoYeon committed
27

28
29
30
31
32
  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
33

Lee SeoYeon's avatar
Lee SeoYeon committed
34
35
36
  async function ansSurvey() {
    try {
      if (surveyId) {
37
        const answersurvey: any = await surveyApi.ansSurvey(surveyId);
Lee SeoYeon's avatar
Lee SeoYeon committed
38
        console.log(answersurvey);
39
        const questionIds = answersurvey.questions.map((el: any) => {
Yoon, Daeki's avatar
Yoon, Daeki committed
40
          return { questionId: el._id, type: el.type, answer: "" };
Jiwon Yoon's avatar
Jiwon Yoon committed
41
42
        });
        console.log(questionIds);
43
        if (answersurvey) {
44
45
46
47
48
          // setResponse({
          //   ...answer,
          //   surveyId: answersurvey._id,
          //   answers: questionIds,
          // });
Yoon, Daeki's avatar
Yoon, Daeki committed
49
50
51
52
          answer.current.surveyId = answersurvey._id;
          answer.current.guestId = answersurvey.guestId;
          answer.current.answers = questionIds;

53
54
55
56
          setSurvey(answersurvey);
          setSuccess(true);
          setError("");
        }
Lee SeoYeon's avatar
Lee SeoYeon committed
57
58
59
60
61
62
63
64
65
66
      } else {
        setLoading(true);
      }
    } catch (error) {
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

Yoon, Daeki's avatar
Yoon, Daeki committed
67
68
69
70
  useEffect(() => {
    ansSurvey();
  }, [surveyId]);

71
  async function handleSubmit(event: FormEvent) {
Jiwon Yoon's avatar
Jiwon Yoon committed
72
    event.preventDefault();
73
74
    try {
      const formData = new FormData();
75
      formData.append("surveyId", answer.current.surveyId);
76
      formData.append("guestId", "");
77
      formData.append("answers", JSON.stringify(answer.current.answers));
78
79
80
81
82
83
84
85
86
87
88
89
      files.map((f) => {
        formData.append("files", f.file);
      });
      const newAnswer: AnswerType = await answerApi.saveAnswers(formData);
      // console.log(newAnswer);
      setSuccess(true);
      setError("");
    } catch (error) {
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
90
91
92
  }

  const handleAnswer = () => {
93
94
95
    console.log("handle answer:", answer.current);
    // const newList = [...answer.answers];
    // setResponse({ ...answer, answers: newList });
Jiwon Yoon's avatar
Jiwon Yoon committed
96
97
  };

Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
98
  return (
Jiwon Yoon's avatar
Jiwon Yoon committed
99
    <>
100
      {console.log("rendering survey form", answer.current)}
Jiwon Yoon's avatar
Jiwon Yoon committed
101
102
103
104
105
106
107
108
109
110
111
      <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>
            {survey.questions.map((question) => {
              return (
                <AQuestion
                  question={question}
Yoon, Daeki's avatar
Yoon, Daeki committed
112
113
114
                  answer={answer.current.answers.find(
                    (ans) => ans.questionId === question._id
                  )}
115
                  addFiles={addFiles}
Jiwon Yoon's avatar
Jiwon Yoon committed
116
117
118
119
120
121
122
123
124
125
126
127
128
                  handleAnswer={handleAnswer}
                ></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
129
        </div>
Jiwon Yoon's avatar
Jiwon Yoon committed
130
131
      </form>
    </>
Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
132
133
  );
};