question.context.tsx 2.19 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
2
3
4
5
6
7
8
import React, {
  createContext,
  FC,
  ReactNode,
  useContext,
  useState,
} from "react";
import axios from "axios";
9
import { BasicQuestionType } from "../types";
Jiwon Yoon's avatar
Jiwon Yoon committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

interface IQuestionContext {
  questionListChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  questionList: BasicQuestionType[];
  editClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
  currentId: string;
  addQuestion: (e: React.MouseEvent<HTMLButtonElement>) => Promise<void>;
}

const QuestionContext = createContext<IQuestionContext>({
  questionListChange: () => {},
  questionList: [],
  editClick: () => {},
  currentId: "",
  addQuestion: async () => {},
});

export const QuestionProvider: FC<{ children: ReactNode }> = ({ children }) => {
  const [questionList, setQuestionList] = useState<Array<BasicQuestionType>>(
    []
  );
  const [currentId, setCurrentId] = useState<string>("");

  function questionListChange(e: React.ChangeEvent<HTMLInputElement>): 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<HTMLButtonElement>) {
    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<HTMLButtonElement>) {
    setCurrentId(e.currentTarget.id);
  }

  return (
    <QuestionContext.Provider
      value={{
        questionListChange,
        addQuestion,
        questionList,
        editClick,
        currentId,
      }}
    >
      {children}
    </QuestionContext.Provider>
  );
};

export const useQuestion = () => useContext(QuestionContext);