question.context.tsx 1.99 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
import { questionApi } from "../apis";
Jiwon Yoon's avatar
Jiwon Yoon committed
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

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);
  }

Jiwon Yoon's avatar
Jiwon Yoon committed
42
  async function addQuestion() {
Jiwon Yoon's avatar
Jiwon Yoon committed
43
    try {
Jiwon Yoon's avatar
Jiwon Yoon committed
44
45
      const newQ: BasicQuestionType = await questionApi.createQuestion();
      setQuestionList([...questionList, newQ]);
Jiwon Yoon's avatar
Jiwon Yoon committed
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
      // 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);