import { useState, useEffect } from 'react';
import { Redirect, useParams } from 'react-router-dom';
import { useAuth } from '../../utils/context';
import BtnGroup from "../Buttons/BtnGroup";
import subjectApi from '../../apis/subject.api';
import catchErrors from '../../utils/catchErrors';
import styles from "./form.module.scss";
const SubjectForm = () => {
const { user } = useAuth();
const { subjectId } = useParams();
const [success, setSuccess] = useState(false)
const [error, setError] = useState("");
const [disabled, setDisabled] = useState(true)
const [subject, setSubject] = useState({
lectureName: "",
prof: "",
classRoom: ""
})
useEffect(() => {
getInfo(subjectId);
}, [])
useEffect(() => {
let isMounted = true;
const checkInfo = { lectureName: subject.lectureName }
if (isMounted) {
const isSubject = Object.values(checkInfo).every((el) => Boolean(el));
isSubject ? setDisabled(false) : setDisabled(true);
}
return () => {
isMounted = false;
}
}, [subject])
function handleChange(e) {
const { name, value } = e.target
setSubject({ ...subject, [name]: value })
}
async function getInfo(id) {
const result = await subjectApi.getSubInfo(id)
setSubject({
lectureName: result.name,
prof: result.prof,
classRoom: result.room
})
}
async function handleSubmit(e) {
e.preventDefault();
try {
setError("")
if (subjectId) {
//수정함수 실행
await subjectApi.editSubject(subject, subjectId)
alert("과목정보가 수정되었습니다.")
setSuccess(true)
} else {
//등록함수 실행
await subjectApi.addsubject(subject, user.id)
}
} catch (error) {
catchErrors(error, setError)
setSubject({
lectureName: "",
prof: "",
classRoom: ""
})
}
}
if (success) {
return