import React, { ChangeEvent, FormEvent, useState } from "react"; import { useNavigate } from "react-router-dom"; import { catchErrors } from "../helpers"; import { SpinnerIcon } from "../icons"; import { CreateQuestionData, ISurvey } from "../types"; import { QuestionsList } from "./QuestionsList"; type Props = { surveyData: ISurvey; callApi: (surveyData: ISurvey) => Promise; }; export const ModifySurvey = ({ surveyData, callApi }: Props) => { const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const [survey, setSurvey] = useState(surveyData); const [questions, setQuestions] = useState(() => { const questions = survey.questions; return questions.map((question) => ({ ...question, isEditing: false })); }); const navigate = useNavigate(); const handleChange = (e: ChangeEvent) => { const { name, value } = e.target; setSurvey({ ...survey, [name]: value }); }; const hasIncompleteEditing = () => { if (questions.length <= 0) { return true; } const incompleted = questions.some((question) => question.isEditing); return incompleted; }; const handleQuestion = (question: CreateQuestionData) => { const index = questions.findIndex((q) => q._id === question._id); if (index < 0) { return; } questions[index] = question; console.log("handle question questions:", questions); setQuestions([...questions]); }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); survey.questions = questions; try { setLoading(true); const result = await callApi(survey); console.log("result:", result); // navigate("/surveys/profile", { replace: true }); navigate(-1); } catch (error) { setLoading(false); catchErrors(error, setError); } }; const addQuestion = () => { const question: CreateQuestionData = { _id: Math.random().toString(), order: questions.length, type: "singletext", title: "", comment: "", isRequired: false, content: { choices: [] }, isEditing: true, }; setQuestions([...questions, question]); }; async function deleteQuestion(id: string) { const delQuestions = questions.filter((question) => question._id !== id); setQuestions(delQuestions); } const disabled = hasIncompleteEditing(); return ( <> {loading && ( )}
{error && (

{error}

)}
); };