import React, { FormEvent, useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import { questionApi, surveyApi } from "../apis"; import { SpinnerIcon } from "../icons"; import { Question } from "../questions"; import { BasicQuestionType, SurveyType } from "../types"; export const EditSurvey = () => { let { surveyId } = useParams<{ surveyId: string }>(); useEffect(() => { getSurvey(); }, [surveyId]); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const [success, setSuccess] = useState(false); const [survey, setSurvey] = useState({ _id: surveyId, user: {}, title: "", comment: "", questions: [], }); const [currentId, setCurrentId] = useState(""); const changeCurrentId = (id: string) => { setCurrentId(id); }; async function getSurvey() { try { if (surveyId) { const thisSurvey: SurveyType = await surveyApi.getSurvey(surveyId); setSurvey(thisSurvey); setSuccess(true); setError(""); } else { setLoading(true); } } catch (error) { console.log("에러발생"); // catchErrors(error, setError) } finally { setLoading(false); } } const handleQuestion = (id: string) => { const newList: BasicQuestionType[] = [...survey.questions]; setSurvey({ ...survey, questions: newList }); }; const handleSurvey = (event: React.ChangeEvent) => { const { name, value } = event.currentTarget; setSurvey({ ...survey, [name]: value }); }; async function handleSubmit(event: FormEvent) { event.preventDefault(); try { const newSurvey: SurveyType = await surveyApi.editSurvey(survey); console.log(newSurvey); // setSuccess(true); // setError(""); } catch (error) { console.log("에러발생"); // catchErrors(error, setError) } finally { // setLoading(false); } } async function addQuestion() { try { const newQuestion: BasicQuestionType = await questionApi.createQuestion(); setSurvey({ ...survey, questions: [...survey.questions, newQuestion] }); // setSuccess(true); // setError(""); } catch (error) { console.log("에러발생"); // catchErrors(error, setError) } finally { // setLoading(false); } } async function deleteQuestion(id: string) { const newList: BasicQuestionType[] = [...survey.questions]; try { const newQuestion: BasicQuestionType = await questionApi.deleteQuestion( id ); setSurvey({ ...survey, questions: newList.filter((a) => a._id !== id) }); // setSuccess(true); // setError(""); } catch (error) { console.log("에러발생"); // catchErrors(error, setError) } finally { // setLoading(false); } } const questions = survey.questions; console.log(questions); return ( <> {loading && ( )}
{questions.map((question) => ( ))}
); };