npx create-next-app@latest
yarn add axios
yarn add json-server
yarn server로 포트 추가 "server": "yarn json-server db.json --port 4000"
{
"todos": [
{ "id": "1", "title": "TODO1", "contents": "sample contents", "isDone": true },
{ "id": "2", "title": "TODO2", "contents": "sample contents", "isDone": false }
],
}
export interface Todo {
id: number;
title: string;
contents: string;
isDone: boolean;
}
☘️ 데이터 가져오기
export const getTodo = async () => {
try {
const res = await axios.get(BASEURL);
return res.data;
} catch (error) {
console.log("fetch error:", error);
}
};
☘️ 데이터 추가하기
export const addTodo = async (newTodo: {
title: string;
contents: string;
isDone: boolean;
}) => {
try {
const res = await axios.post(BASEURL, newTodo);
return res.data;
} catch (error) {
console.log("addError:", error);
}
};
☘️ 데이터 수정하기
export const patchTodo = async ({
id,
isDone,
}: Pick<Todo, "id" | "isDone">) => {
try {
const res = await axios.patch(`${BASEURL}/${id}`, { isDone: !isDone });
return res.data;
} catch (error) {
console.log(error);
}
};```
☘️ 데이터 삭제하기
```ts
export const deleteTodo = async (id: number) => {
try {
const res = await axios.delete(`${BASEURL}/${id}`);
return res.data;
} catch (error) {
console.log("deleteError:", error);
}
};
문제 : 데이터를 추가하는 로직을 작성한 후 이벤트에도 type을 설정해야하는 것을 알았다.
해결 : e: React.FormEvent 추가 후 any에서 벗어남!
문제 : {title:string; contents:string;} 형식의 인수는
{title:string; contents:string; isDone : boolean}
is Done속성이 없다는 typeError가 났다.
해결 : 내가 api를 호출하는 로직에서 isDone까지 로직을 작성하였는데
page.tsx에서 작성하지 않아 생긴 문제
내가 놓치고 가는 부분들을 확실하게 typescript에서 잡아주는 점이 좋았다.
// 데이터 추가하기
const handleAddTodo = async (e) => {
e.preventDefault();
const newTodo = { title, contents };
const data = await addTodo(newTodo);
setTodo((prev) => [...prev, data]);
setTitle("");
setContents("");
};
fix ver.
// 데이터 추가하기
const handleAddTodo = async (e: React.FormEvent) => {
e.preventDefault();
const newTodo = { title, contents, isDone: false };
const data = await addTodo(newTodo);
setTodo((prev) => [...prev, data]);
setTitle("");
setContents("");
};
문제점 : TodoCard.tsx 컴포넌트를 만들었다.
props로 받아오는 과정에서 type오류가 많이 발생했다.
// 맨 처음 작성한 코드
import { Todo } from "@/type/todo";
import React from "react";
interface TodoProps {
todo: Todo[];
onDelete: (id: number) => void;
onPatch: (id: number, isDone: boolean) => void;
}
const Todocard: <TodoProps> = ({ todo, onDelete, onPatch }) => {
return (
<li>
<p>{todo.title}</p>
</li>
);
};
export default Todocard;
React.FC를 붙이지 않아 오류가 났다.해결방법
import { Todo } from "@/type/todo";
import React from "react";
interface TodoProps {
todo: Todo;
onDelete: (id: number) => void;
onPatch: (id: number, isDone: boolean) => void;
}
const Todocard: React.FC<TodoProps> = ({ todo, onDelete, onPatch }) => {
return (
<li>
<p>{todo.title}</p>
<p>{todo.contents}</p>
<button onClick={() => onDelete(todo.id)}>삭제</button>
<button onClick={() => onPatch(todo.id, todo.isDone)}>
{!todo.isDone ? "완료" : "취소"}
</button>
</li>
);
};
export default Todocard;