pages
import { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { useForm } from "react-hook-form";
import { postBlogCategory, getAllBlogCategory } from "../../api/blogCategory";
const BlogCategoryCreate = () => {
const [error, setError] = useState(200);
const [category, setCategory] = useState([]);
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
const navigate = useNavigate();
const location = useLocation();
useEffect(async () => {
const {
data: { data },
} = await getAllBlogCategory();
setCategory(data);
}, []);
const onSubmit = async (data) => {
// 요청 보낼 때
try {
if (data.parentId === "default") delete data.parentId;
const res = await postBlogCategory(data);
if (res.data.id) navigate(`${location.state.from.pathname}`);
} catch (e) {
if (e.response.data.error === "Conflict") setError(409);
throw e;
}
};
return (
<section>
<h1>블로그 카테고리 추가</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="parentId">상위 카테고리:</label>
<div className="select">
<select
defaultValue="default"
name="parentId"
id="parentId"
{...register("parentId")}
>
<option value="default">
없음
</option>
{category.map((item) => {
return <option key={item.id} value={item.id}>
{item.name}
</option>;
})}
</select>
</div>
<label htmlFor="name">이름:</label>
<input
{...register("name", { required: true })}
type="text"
id="name"
/>
<p>{errors.name?.type === "required" && "이름은 필수입니다."}</p>
<button>추가</button>
{error === 409 ? <p>이미 존재하는 계정입니다.</p> : ""}
</form>
</section>
);
};
postBlogCategory
export const postBlogCategory = async (data) => {
try {
return await axiosAPI.post(URL, data, {
headers: { Authorization: localStorage.getItem("token") },
});
} catch (e) {
throw e;
}
};
axios
import axios from "axios";
export const BASE_URL = "http://localhost:5001/api/admin";
export const axiosAPI = axios.create({
baseURL: BASE_URL,
headers: {
Authorization: localStorage.getItem("token"),
"Content-Type": "application/json",
},
withCredentials: true,
});
const apiRouter = async (method, url, request) => {
return await axiosAPI({
method,
url,
data: request,
})
};
const get = async (url, request) => await apiRouter("get", url, request);
const post = async (url, request) => await apiRouter("post", url, request);
const put = (url, request) => apiRouter("put", url, request);
const deleted = (url, request) => apiRouter("delete", url, request);
export const API = {
get,
post,
put,
deleted,
};
parentId가 없을 때는 잘 저장되는데 parentid를 설정후 저장을 누르면 400 오류가 발생합니다. postBlogCategory까지는 전달이 되는데 axios에 전달이 안되는것 같습니다. 어디를 고쳐야 하는지 알려주시면 감사하겠습니다.