'use client'
import { useState, useEffect } from 'react'
export const dynamic = 'force-dynamic'
interface Todo {
id: string
title: string
completed: boolean
createdAt: string
}
export default function Home() {
const [todos, setTodos] = useState<Todo[]>([])
const [newTodo, setNewTodo] = useState('')
// Load todos on mount
useEffect(() => {
fetch('/api/todos')
.then(res => res.json())
.then(setTodos)
}, [])
// Add a new todo
async function addTodo(e: React.FormEvent) {
e.preventDefault()
if (!newTodo.trim()) return
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: newTodo })
})
const todo = await res.json()
setTodos([todo, ...todos])
setNewTodo('')
}
// Toggle completion
async function toggleTodo(id: string, completed: boolean) {
await fetch(`/api/todos/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ completed: !completed })
})
setTodos(todos.map(t =>
t.id === id ? { ...t, completed: !completed } : t
))
}
// Delete a todo
async function deleteTodo(id: string) {
await fetch(`/api/todos/${id}`, { method: 'DELETE' })
setTodos(todos.filter(t => t.id !== id))
}
return (
<main style={{ maxWidth: 600, margin: '0 auto', padding: 20 }}>
<h1>My Todos</h1>
<form onSubmit={addTodo} style={{ marginBottom: 20 }}>
<input
value={newTodo}
onChange={e => setNewTodo(e.target.value)}
placeholder="What needs to be done?"
style={{ padding: 10, width: '70%', marginRight: 10 }}
/>
<button type="submit" style={{ padding: '10px 20px' }}>
Add
</button>
</form>
<ul style={{ listStyle: 'none', padding: 0 }}>
{todos.map(todo => (
<li
key={todo.id}
style={{
display: 'flex',
alignItems: 'center',
padding: 10,
borderBottom: '1px solid #eee'
}}
>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(todo.id, todo.completed)}
style={{ marginRight: 10 }}
/>
<span style={{
flex: 1,
textDecoration: todo.completed ? 'line-through' : 'none',
color: todo.completed ? '#999' : 'inherit'
}}>
{todo.title}
</span>
<button
onClick={() => deleteTodo(todo.id)}
style={{ color: 'red', border: 'none', cursor: 'pointer' }}
>
Delete
</button>
</li>
))}
</ul>
{todos.length === 0 && (
<p style={{ color: '#999', textAlign: 'center' }}>
No todos yet. Add one above!
</p>
)}
</main>
)
}