File size: 1,209 Bytes
cce8120 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import React, { useEffect, useState } from 'react';
import axios from 'axios';
import TodoList from './components/TodoList';
import TodoForm from './components/TodoForm';
const API_URL = 'http://localhost:8000/api/todos';
function App() {
const [todos, setTodos] = useState([]);
const fetchTodos = async () => {
const response = await axios.get(API_URL);
setTodos(response.data);
};
useEffect(() => {
fetchTodos();
}, []);
const addTodo = async (title) => {
const response = await axios.post(API_URL, { title });
setTodos([...todos, response.data]);
};
const toggleTodo = async (id, completed) => {
const todo = todos.find(t => t.id === id);
const response = await axios.put(`${API_URL}/${id}`, { title: todo.title, completed });
setTodos(todos.map(t => (t.id === id ? response.data : t)));
};
const deleteTodo = async (id) => {
await axios.delete(`${API_URL}/${id}`);
setTodos(todos.filter(t => t.id !== id));
};
return (
<div style={{ padding: '2rem' }}>
<h1>Todo List</h1>
<TodoForm onAdd={addTodo} />
<TodoList todos={todos} onToggle={toggleTodo} onDelete={deleteTodo} />
</div>
);
}
export default App;
|