π App.jsx
import { useEffect, useState } from "react";
import "./App.css";
import axios from "axios";
function App() {
const [todos, setTodos] = useState(null);
const fetchTodos = async () => {
const { data } = await axios.get("http://localhost:4000/todos");
setTodos(data);
};
useEffect(() => {
// dbλ‘λΆν° κ°μ κ°μ Έμ¬ κ²μ΄λ€
fetchTodos();
}, []);
return (
<>
<div>
{/* input μμ */}
<form>
<input type="text" />
<button>μΆκ°</button>
</form>
</div>
<div>
{/* λ°μ΄ν° μμ */}
{todos ? (
todos.map((item) => (
<div key={item.id}>
{item.id} : {item.title}
</div>
))
) : (
<p>Loading...</p>
)}
</div>
</>
);
}
export default App;
π App.jsx
import { useEffect, useState } from "react";
import "./App.css";
import axios from "axios";
function App() {
const [todos, setTodos] = useState(null);
const [inputValue, setInputValue] = useState({
title: "",
});
const [targetId, setTargetId] = useState("");
const [contents, setContents] = useState("");
// μ‘°ν ν¨μ
const fetchTodos = async () => {
const { data } = await axios.get("http://localhost:4000/todos");
setTodos(data);
};
// μΆκ° ν¨μ
const onSubmitHandler = async () => {
axios.post("http://localhost:4000/todos", inputValue);
// setTodos([...todos, inputValue]); // νλ©΄μ idκ°μ΄ λ°λ‘ λ¨μ§ μλλ€.
fetchTodos(); // DBλ₯Ό λ€μ μ½μ΄μ¨λ€.
setInputValue({ title: "" });
};
// μμ ν¨μ
const onDeleteButtonClickHandler = async (id) => {
axios.delete(`http://localhost:4000/todos/${id}`);
setTodos(
todos.filter((item) => {
return item.id !== id;
})
);
};
//μμ ν¨μ
const onUpdateButtonClickHandler = async () => {
axios.patch(`http://localhost:4000/todos/${targetId}`, {
title: contents,
});
setTodos(
todos.map((item) => {
if (item.id == targetId) {
return { ...item, title: contents };
} else {
return item;
}
})
);
};
useEffect(() => {
// dbλ‘λΆν° κ°μ κ°μ Έμ¬ κ²μ΄λ€
fetchTodos();
}, []);
return (
<>
<div>
{/* μμ μμ */}
<div>
<input
type="text"
placeholder="μμ ν μμ΄λ"
value={targetId}
onChange={(e) => {
setTargetId(e.target.value);
}}
/>
<input
type="text"
placeholder="μμ ν λ΄μ©"
value={contents}
onChange={(e) => {
setContents(e.target.value);
}}
/>
<button onClick={onUpdateButtonClickHandler}>μμ </button>
<br />
<br />
<br />
</div>
{/* input μμ */}
<form
onSubmit={(e) => {
e.preventDefault(); // λ²νΌμ λλ μ λ μλ‘κ³ μΉ¨μ λ§λλ€.
// λ²νΌ ν΄λ¦ μ , inputμ λ€μ΄μλ κ°(state)μ μ΄μ©νμ¬ DBμ μ μ₯(postμμ²)
onSubmitHandler();
}}
>
<input
type="text"
value={inputValue.title}
onChange={(e) => {
setInputValue({
title: e.target.value,
});
}}
/>
<button type="submit">μΆκ°</button>
</form>
</div>
<div>
{/* λ°μ΄ν° μμ */}
{todos ? (
todos.map((item) => (
<div key={item.id}>
{item.id} : {item.title}
<button onClick={() => onDeleteButtonClickHandler(item.id)}>
μμ
</button>
</div>
))
) : (
<p>Loading...</p>
)}
</div>
</>
);
}
export default App;