import { useEffect, useState } from "react"; import { Session } from "@supabase/supabase-js"; import { supabase } from "../utils/supabase"; import "./TodoList.css"; interface ITodo { id: number; task: string; is_complete: boolean; user_id: string; } export default function TodoList({ session }: { session: Session }) { const [todos, setTodos] = useState([]); const [newTaskText, setNewTaskText] = useState(""); const [errorText, setErrorText] = useState(""); const user = session.user; useEffect(() => { const fetchTodos = async () => { const { data: todos, error } = await supabase .from("todos") .select("*") .eq("user_id", user.id) .order("id", { ascending: true }); if (error) console.log("error", error); else setTodos(todos); }; fetchTodos(); }, []); const addTodo = async (taskText: string) => { let task = taskText.trim(); if (task.length) { const { data: todo, error } = await supabase .from("todos") .insert({ task, user_id: user.id, is_complete: false }) .select() .single(); if (error) { setErrorText(error.message); } else { setTodos([...todos, todo]); setNewTaskText(""); } } }; const deleteTodo = async (id: number) => { try { await supabase.from("todos").delete().eq("id", id).throwOnError(); setTodos(todos.filter((x) => x.id != id)); } catch (error) { console.log("error", error); } }; return (

My Tasks

{ e.preventDefault(); addTodo(newTaskText); }} className="todo-form" > { setErrorText(""); setNewTaskText(e.target.value); }} />
{!!errorText && } {todos.length === 0 ? (

No tasks yet. Add a new task to get started.

) : (
    {todos.map((todo) => ( deleteTodo(todo.id)} /> ))}
)}
); } const Todo = ({ todo, onDelete }: { todo: ITodo; onDelete: () => void }) => { const [isCompleted, setIsCompleted] = useState(todo.is_complete); const toggle = async () => { try { const { data } = await supabase .from("todos") .update({ is_complete: !isCompleted }) .eq("id", todo.id) .throwOnError() .select() .single(); if (data) setIsCompleted(data.is_complete); } catch (error) { console.log("error", error); } }; return (
  • toggle()} type="checkbox" checked={isCompleted} />

    {todo.task}

  • ); }; const Alert = ({ text }: { text: string }) => (
    {text}
    );