import React, { useCallback, useEffect, useMemo, useState } from "react"; import { NextPage } from "next"; import { useRouter } from "next/router"; import { TodoClient, Todos } from "../util/TodoClient"; import styles from "../styles/Todo.module.css"; const api = process.env.NEXT_PUBLIC_TODO_API!; const Todo: NextPage = () => { const client = useMemo(() => new TodoClient(api), []); const router = useRouter(); const [todos, setTodos] = useState([]); const [description, setDescription] = useState(""); const [error, setError] = useState(null); const addTodo = (event: React.FormEvent) => { event.preventDefault(); const todo = { description, checked: false }; client .addTodo(todo) .then((res) => { if (res.status === 401) { router.replace("/").catch((e) => setError(e)); return; } setDescription(""); listTodos(); return; }) .catch((e) => { setError(e); }); }; const listTodos = useCallback(() => { client .listTodos() .then((res) => { if (res.status === 401) { router.push("/").catch((e) => setError(e)); return; } return res.json(); }) .then((todo) => { if (todo) { setTodos(todo); } }) .catch((e) => { setError(e); }); }, [client, router]); const patchTodo = (id: string, checked: boolean) => { client .patchTodo(id, checked) .then((res) => { if (res.status === 401) { router.push("/").catch((e) => setError(e)); return; } listTodos(); return; }) .catch((e) => { setError(e); }); }; const deleteTodo = (id: string) => { client .deleteTodo(id) .then((res) => { if (res.status === 401) { router.push("/").catch((e) => setError(e)); return; } listTodos(); return; }) .catch((e) => { setError(e); }); }; const logout = () => { client .logout() .then(() => { router.push("/").catch((e) => setError(e)); return; }) .catch((e) => { setError(e); }); }; const profile = () => { router.push("/profile").catch(setError) } const changeDescription = (event: React.ChangeEvent) => { setDescription(event.currentTarget.value); }; const changeCheckbox = (event: React.ChangeEvent) => { const { currentTarget } = event; patchTodo(currentTarget.value, currentTarget.checked); }; useEffect(() => { listTodos(); }, [listTodos]); return ( <>

Todos

{error?.message}
{todos.map((todo, index) => (
))}
); }; export default Todo;