반응형
# 데이터를 만들어 넣고 리액트 화면에 할일이 나오도록 json-server를 실행
// data.json
{
"items": [
{
"id": 1,
"task": "자기",
"due": "20210901",
"status": "done"
},
{
"id": 2,
"task": "청소하기",
"due": "20210902",
"status": "done"
},
{
"id": 3,
"task": "공부하기",
"due": "20210903",
"status": "done"
},
{
"id": 4,
"task": "달리기",
"due": "20210904",
"status": "done"
},
{
"id": 5,
"task": "숙제하기",
"due": "20210905",
"status": "todo"
},
{
"id": 6,
"task": "수업듣기",
"due": "20220901",
"status": "todo"
},
{
"id": 7,
"task": "밥먹기",
"due": "20220101",
"status": "todo"
},
{
"id": 8,
"task": "자기",
"due": "20220301",
"status": "done"
},
{
"id": 9,
"task": "공부하기",
"due": "20220501",
"status": "done"
},
{
"id": 10,
"task": "게임하기",
"due": "20221031",
"status": "done"
}
]
}
npx json-server --watch ./src/db/data.json --port 3001
localhost:3001/items
localhost:3001/items?status=todo
localhost:3001/items?status =done
# 백엔드 API를 리액트앱과 연결
//items.js
import { useState, useEffect } from "react";
import Item from "./Item";
export default function Items({endpoint =""}) {
const [data, setData] = useState([]);
useEffect(() => {
fetch(`http://localhost:3001/items${endpoint}`)
.then((res) => {
return res.json();
})
.then((json_response) => {
setData(json_response);
});
});
return (
<table>
<td></td>
<td>Task</td>
<td>Due</td>
<td>Status</td>
{data.map(
(item) => {
return <Item key={item.id} item={item}/>
}
)}
</table>
);
}
# Json 파일에 데이터를 추가하자
// Createitem.js
import { useState } from "react";
import { useNavigate } from "react-router";
export default function CreateItem() {
const [values, setValues] = useState({
task: "",
due: "",
});
return (
<form>
<div className="input_area">
<label>Task</label>
<input type="text" name="task" value={values.task} />
</div>
<div className="input_area">
<label>Due</label>
<input type="text" name="due" value={values.due} />
</div>
<button>Create</button>
</form>
);
}
//CreateItem.js
import { useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
export default function CreateItem() {
const [values, setValues] = useState({
task: "",
due: "",
});
const handleChange = (event) => {
const { name, value } = event.target;
setValues({
...values,
[name]: value,
});
};
const navigate = useNavigate();
const onSubmit = (event) => {
event.preventDefault();
fetch("http://localhost:3001/items", {
method: "POST",
headers: {
"Content-Type" : "application/json"
},
body: JSON.stringify({
task: values.task,
due: values.due,
status: "todo",
}),
}).then((res)=>{
if(res.ok){
alert("Created new item!");
navigate("/todo");
}
});
};
return (
<form onSubmit ={onSubmit}>
<div className="input_area">
<label>Task</label>
<input
type="text"
name="task"
value={values.task}
onChange={handleChange}
/>
</div>
<div className="input_area">
<label>Due</label>
<input
type="text"
name="due"
value={values.due}
onChange={handleChange}
/>
</div>
<button>Create</button>
</form>
);
}
# Json 파일에 데이터를 삭제하자
//Item.js
import { useState } from "react";
export default function Item({ item: i }) {
const [item, setItem] = useState(i);
const toggle = () => {
fetch(`http://localhost:3001/items/${item.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
...item,
status: item.status ==="done"? "todo" : "done",
})
}).then((res) => {
if (res.ok) {
setItem({
...item,
status: item.status ==="done"? "todo" : "done",
});
}
});
};
const deleteItem = () => {
if (window.confirm("삭제 하시겠습니까?")) {
fetch(`http://localhost:3001/items/${item.id}`, {
method: "DELETE",
}).then((res) => {
if (res.ok) {
setItem({ id: 0 });
}
});
}
};
if (item.id === 0) {
return null;
}
return (
<tr>
<td>
<input
type="checkbox"
checked={item.status === "done" ? true : false}
onClick={toggle}
></input>
</td>
<td>{item.task}</td>
<td>{item.due}</td>
<td>
<button onClick={deleteItem}>Delete</button>
</td>
</tr>
);
}
# 페이지마다 URL을 지정하는 방법
//App.js
import React from "react";
import Items from "./components/Items";
import Users from "./components/Users";
import Header from "./components/Header";
import CreateItem from "./components/CreateItem";
import { BrowserRouter, Route, Routes } from "react-router-dom";
export default function App() {
return (
<BrowserRouter>
<div className="App">
<Header />
<Routes>
<Route path="/" element={<Items />} />
{/* <Route path="/user" element={<Users />} /> */}
<Route path="/todo" element={<Items endpoint="?status=todo"/>} />
<Route path="/done" element={<Items endpoint="?status=done"/>} />
<Route path="/create_item" element={<CreateItem />} />
</Routes>
</div>
</BrowserRouter>
);
}
//Header.js
import { Link } from "react-router-dom";
export default function Header() {
return (
<div className="header">
<h1>
<Link to="/">todo-list</Link>
</h1>
<div className="menu">
{/*
<Link to="/user" className="link">
<button>Users</button>
</Link>
*/}
<Link to="/todo" className="link">
<button>Todo</button>
</Link>
<Link to="/done" className="link">
<button>Done</button>
</Link>
<Link to="/create_item" className="link">
<button>Add</button>
</Link>
</div>
</div>
);
}
//Items.js
import { useState, useEffect } from "react";
import Item from "./Item";
export default function Items({endpoint =""}) {
const [data, setData] = useState([]);
useEffect(() => {
fetch(`http://localhost:3001/items${endpoint}`)
.then((res) => {
return res.json();
})
.then((json_response) => {
setData(json_response);
});
});
return (
<table>
<td></td>
<td>Task</td>
<td>Due</td>
<td>Status</td>
{data.map(
(item) => {
return <Item key={item.id} item={item}/>
}
)}
</table>
);
}
< Todo page >
< Done page >
<Add page >
반응형
'코딩 알로하 :: one > react.js' 카테고리의 다른 글
react 공식 문서 (0) | 2022.06.03 |
---|---|
Stack Overflow Developer Survey 2021 (0) | 2022.06.02 |
리액트 To-do 리스트 만들기 (5탄) (0) | 2022.06.01 |
리액트 To-do 리스트 만들기 (4탄) (0) | 2022.06.01 |
리액트 To-do 리스트 만들기 (3탄) (0) | 2022.06.01 |
댓글