import React, { createContext, FC, ReactNode, useContext, useState, } from "react"; import axios from "axios"; import { BasicQuestionType } from "./CreateSurveyFormPage"; interface IQuestionContext { questionListChange: (e: React.ChangeEvent) => void; questionList: BasicQuestionType[]; editClick: (e: React.MouseEvent) => void; currentId: string; addQuestion: (e: React.MouseEvent) => Promise; } const QuestionContext = createContext({ questionListChange: () => {}, questionList: [], editClick: () => {}, currentId: "", addQuestion: async () => {}, }); export const QuestionProvider: FC<{ children: ReactNode }> = ({ children }) => { const [questionList, setQuestionList] = useState>( [] ); const [currentId, setCurrentId] = useState(""); function questionListChange(e: React.ChangeEvent): void { const newList: BasicQuestionType[] = [...questionList]; const obj: any = newList.find((a) => a._id === e.target.id); //고유 _id로 질문찾기 const targetKey: any = e.target.name; obj[targetKey] = e.target.value; setQuestionList(newList); } async function addQuestion(e: React.MouseEvent) { try { const res = await axios.post("/api/questions/create", { type: "essay", title: "Question Title", isRequired: false, comment: "질문에 대한 설명을 입력해주세요", content: null, }); console.log(res.data); setQuestionList([...questionList, res.data]); // setSuccess(true); // setError(""); } catch (error) { console.log("에러발생"); // catchErrors(error, setError) } finally { // setLoading(false); } } function editClick(e: React.MouseEvent) { setCurrentId(e.currentTarget.id); } return ( {children} ); }; export const useQuestion = () => useContext(QuestionContext);