import { useEffect, useState } from "react";
export default function App() {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState({
subject: "",
details: ""
});
useEffect(() => {
(async () => {
try {
const response = await fetch(
"https://todo-app-seir.herokuapp.com/todos/"
);
const data = await response.json();
setTodos(data);
} catch (error) {
console.error(error);
}
})();
}, []);
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch(
"https://todo-app-seir.herokuapp.com/todos/",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newTodo)
}
);
const data = await response.json();
setTodos([...todos, data]);
setNewTodo({
subject: "",
details: ""
});
} catch (error) {
console.error(error);
}
};
const handleDelete = async (e, id, idx) => {
try {
const response = await fetch(
`https://todo-app-seir.herokuapp.com/todos/${id}/`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json"
}
}
);
const data = response.json();
const copyTodos = [...todos];
copyTodos.splice(idx, 1);
setTodos(copyTodos);
} catch (error) {
console.error(error);
}
};
const handleChange = (e) => {
setNewTodo({ ...newTodo, [e.target.name]: e.target.value });
};
return (
<div className="App">
{todos.map((todo, idx) => (
<h1 key={todo.id}>
<span>{todo.subject}</span> <span>{todo.details}</span>
<button
onClick={(e) => {
handleDelete(e, todo.id, idx);
}}
>
DELETE ME
</button>
</h1>
))}
<form onSubmit={handleSubmit}>
<label>
Subject:{" "}
<input
type="text"
name="subject"
value={newTodo.subject}
onChange={handleChange}
/>
</label>
<label>
Details:{" "}
<input
type="text"
name="details"
value={newTodo.details}
onChange={handleChange}
/>
</label>
<br />
<input type="submit" />
</form>
</div>
);
}