SurveyForm.tsx 4.34 KB
Newer Older
1
import React, { FormEvent, useEffect, useRef, useState } from "react";
2
import { Link, useNavigate } from "react-router-dom";
Lee SeoYeon's avatar
Lee SeoYeon committed
3
import { useParams } from "react-router-dom";
4
import { surveyApi, answerApi } from "../apis";
Lee SeoYeon's avatar
Lee SeoYeon committed
5
import { catchErrors } from "../helpers";
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 }[]>([]);
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
17
18
19
20
21
22
  const [survey, setSurvey] = useState<SurveyType>({
    _id: surveyId,
    user: {},
    title: "",
    comment: "",
    questions: [],
  });
23
24

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

30
31
32
33
34
35
36
  const isSurvey = localStorage.getItem(`survey_${surveyId}`);
  if (isSurvey) {
    console.log("object", isSurvey);
    alert("제출한 설문조사입니다");
    navigate("/");
  }

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

Lee SeoYeon's avatar
Lee SeoYeon committed
43
44
45
  async function ansSurvey() {
    try {
      if (surveyId) {
46
        const answersurvey: any = await surveyApi.ansSurvey(surveyId);
Lee SeoYeon's avatar
Lee SeoYeon committed
47
        console.log(answersurvey);
48
        const questionIds = answersurvey.questions.map((el: any) => {
Yoon, Daeki's avatar
Yoon, Daeki committed
49
          return { questionId: el._id, type: el.type, answer: "" };
Jiwon Yoon's avatar
Jiwon Yoon committed
50
51
        });
        console.log(questionIds);
52
        if (answersurvey) {
53
54
55
56
57
          // setResponse({
          //   ...answer,
          //   surveyId: answersurvey._id,
          //   answers: questionIds,
          // });
Yoon, Daeki's avatar
Yoon, Daeki committed
58
59
60
61
          answer.current.surveyId = answersurvey._id;
          answer.current.guestId = answersurvey.guestId;
          answer.current.answers = questionIds;

62
63
64
65
          setSurvey(answersurvey);
          setSuccess(true);
          setError("");
        }
Lee SeoYeon's avatar
Lee SeoYeon committed
66
67
68
69
70
71
72
73
74
75
      } else {
        setLoading(true);
      }
    } catch (error) {
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

Yoon, Daeki's avatar
Yoon, Daeki committed
76
77
78
79
  useEffect(() => {
    ansSurvey();
  }, [surveyId]);

80
  async function handleSubmit(event: FormEvent) {
Jiwon Yoon's avatar
Jiwon Yoon committed
81
    event.preventDefault();
82
83
    try {
      const formData = new FormData();
84
      formData.append("surveyId", answer.current.surveyId);
85
      formData.append("guestId", "");
86
      formData.append("answers", JSON.stringify(answer.current.answers));
87
88
89
90
      files.map((f) => {
        formData.append("files", f.file);
      });
      const newAnswer: AnswerType = await answerApi.saveAnswers(formData);
91
92
93
      localStorage.setItem(`survey_${surveyId}`, surveyId ?? "");
      alert("제출되었습니다");
      navigate(`/`);
94
95
96
97
98
99
100
101
      // console.log(newAnswer);
      setSuccess(true);
      setError("");
    } catch (error) {
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
102
103
104
  }

  const handleAnswer = () => {
105
106
107
    console.log("handle answer:", answer.current);
    // const newList = [...answer.answers];
    // setResponse({ ...answer, answers: newList });
Jiwon Yoon's avatar
Jiwon Yoon committed
108
109
  };

Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
110
  return (
Jiwon Yoon's avatar
Jiwon Yoon committed
111
    <>
112
      {console.log("rendering survey form", answer.current)}
Jiwon Yoon's avatar
Jiwon Yoon committed
113
114
115
116
117
118
119
120
121
122
123
      <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
124
125
126
                  answer={answer.current.answers.find(
                    (ans) => ans.questionId === question._id
                  )}
127
                  addFiles={addFiles}
Jiwon Yoon's avatar
Jiwon Yoon committed
128
129
130
131
132
133
134
135
136
137
138
139
140
                  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
141
        </div>
Jiwon Yoon's avatar
Jiwon Yoon committed
142
143
      </form>
    </>
Lee SeoYeon's avatar
0708    
Lee SeoYeon committed
144
145
  );
};